Home
DSA Patterns
Graphs (Topological Sort)
Keys and Rooms
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.
- Open room 0 and push it on a stack.
- Pop a room and read its keys. Every key to a room that is still locked opens that room: mark it and push it.
- 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 is unlocked. Mark it open and put it on the stack
Next
Pop room 0: it holds key 1
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
