Browse curriculum

Keys and Rooms (LeetCode 841)

Keys and Rooms (LeetCode 841): room 0 is unlocked and every room holds keys to other rooms. Search from room 0 through the keys you find, and check whether every room gets opened.

Problem Understanding

Keys and Rooms (LeetCode 841): there are n rooms labelled 0 to n − 1, and all are locked except room 0. Each room holds a set of keys, rooms[i], and a key with number j unlocks room j. Return true if you can visit every room.

Examples: [[1],[2],[3],[]] → true (each room holds the next key); [[1,3],[3,0,1],[2],[0]] → false (the only key to room 2 is inside room 2).

The Intuition: Reachability From Room 0

A key is an arrow from the room it lies in to the room it opens. The rooms you can visit are exactly the rooms reachable from room 0 along those arrows.

  1. Open room 0 and push it on a stack.
  2. Pop a room and read its keys. Every key to a room that is still locked opens that room: mark it and push it.
  3. When the stack is empty, nothing more can be opened. Compare the number of open rooms with n.

This is the same graph search as Number of Provinces and Clone Graph, run once from a single start node.

Keys and Rooms Visualization

ARROW = A KEY, POINTING AT THE ROOM IT OPENS · GREEN = OPEN

ROOM 0 IS OPEN

open

1 / 4

Answer

:

stack (top last)

room 0

 

Room 0 is unlocked. Mark it open and put it on the stack

Next

Pop room 0: it holds key 1

Free preview: the first 3 of 9 steps

rooms

Rooms are nodes and keys are arrows to the room they open. Open rooms turn green, rooms waiting on the stack are outlined, and the key being read is blue. Rooms that are still locked when the stack runs out turn red. Try Example 2 and Two islands, where part of the graph cannot be reached.

Keys and Rooms Dry Run

Input: rooms = [[1],[2],[3],[]].

Pop Keys inside Newly opened Stack after
room 0 1 1 [1]
room 1 2 2 [2]
room 2 3 3 [3]
room 3 none none []

All 4 rooms are open.

Answer: true.

Keys and Rooms LeetCode Solution

A stack-based DFS from room 0 with an opened set; count the rooms at the end.

Keys and Rooms Code
1var canVisitAllRooms = function(rooms) {
2 const opened = new Set([0]);
3 const stack = [0];
4 while (stack.length > 0) {
5 const room = stack.pop();
6 for (const key of rooms[room]) {
7 if (!opened.has(key)) {
8 opened.add(key);
9 stack.push(key);
10 }
11 }
12 }
13 return opened.size === rooms.length;
14};

Keys and Rooms in Python, Java, C++, TypeScript and C

Keys and Rooms in Python
class Solution:
    def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
        opened = {0}
        stack = [0]
        while stack:
            room = stack.pop()
            for key in rooms[room]:
                if key not in opened:
                    opened.add(key)
                    stack.append(key)
        return len(opened) == len(rooms)
Keys and Rooms in Java
class Solution {
    public boolean canVisitAllRooms(List<List<Integer>> rooms) {
        boolean[] opened = new boolean[rooms.size()];
        opened[0] = true;
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(0);
        int count = 1;
        while (!stack.isEmpty()) {
            int room = stack.pop();
            for (int key : rooms.get(room)) {
                if (!opened[key]) {
                    opened[key] = true;
                    count++;
                    stack.push(key);
                }
            }
        }
        return count == rooms.size();
    }
}
Keys and Rooms in C++
class Solution {
public:
    bool canVisitAllRooms(vector<vector<int>>& rooms) {
        vector<bool> opened(rooms.size(), false);
        opened[0] = true;
        vector<int> stack = {0};
        int count = 1;
        while (!stack.empty()) {
            int room = stack.back();
            stack.pop_back();
            for (int key : rooms[room]) {
                if (!opened[key]) {
                    opened[key] = true;
                    count++;
                    stack.push_back(key);
                }
            }
        }
        return count == (int)rooms.size();
    }
};
Keys and Rooms in TypeScript
function canVisitAllRooms(rooms: number[][]): boolean {
    const opened = new Set<number>([0]);
    const stack: number[] = [0];
    while (stack.length > 0) {
        const room = stack.pop()!;
        for (const key of rooms[room]) {
            if (!opened.has(key)) {
                opened.add(key);
                stack.push(key);
            }
        }
    }
    return opened.size === rooms.length;
}
Keys and Rooms in C
bool canVisitAllRooms(int** rooms, int roomsSize, int* roomsColSize) {
    bool* opened = calloc(roomsSize, sizeof(bool));
    int* stack = malloc(roomsSize * sizeof(int));
    int top = 0, count = 1;
    opened[0] = true;
    stack[top++] = 0;
    while (top > 0) {
        int room = stack[--top];
        for (int j = 0; j < roomsColSize[room]; j++) {
            int key = rooms[room][j];
            if (!opened[key]) {
                opened[key] = true;
                count++;
                stack[top++] = key;
            }
        }
    }
    free(opened);
    free(stack);
    return count == roomsSize;
}

Edge Cases & Common Mistakes

  • Forgetting to mark room 0: a key back to room 0 would push it again.
  • Keys to rooms already open: skip them, or a cycle like 0 → 1 → 0 loops forever.
  • A key in its own room: it opens nothing new and is skipped like any other open room.
  • Rooms with no keys: the search just moves on to the next room on the stack.

Summary

Treat keys as edges and search from room 0, opening each locked room once. Every room can be visited exactly when the search opens all n of them. O(rooms + keys) time, O(rooms) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start in room 0

    Mark room 0 open and push it on a stack.

  2. Use every key

    Pop a room; for each key to a room not yet open, open that room and push it.

  3. Check

    When the stack is empty, return whether the number of open rooms equals the number of rooms.

Frequently asked questions

Why is Keys and Rooms a graph problem?

Each room is a node, and a key in room i to room j is a directed edge i → j: being in i lets you reach j. "Can you visit every room?" is then "is every node reachable from node 0?", which one DFS or BFS answers.


Should I use DFS or BFS?

Either works and both are O(rooms + keys): the order rooms are opened changes, the set of rooms opened does not. The stack version shown here is a DFS; swap the stack for a queue and it becomes a BFS. A recursive DFS works too.


Why mark a room open when it is pushed, not when it is popped?

Marking on push means a room enters the stack at most once, so the stack never holds more than n rooms and no room’s keys are read twice. Marking on pop is still correct but can push the same room several times.

New to the technique behind this problem? Watch it run step by step:

Topological Sort Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description