Keys and Rooms solution explained
Keys and Rooms asks whether you can enter every room when only room 0 starts unlocked and each room holds keys to other rooms. Treat each room as a node and each key as a directed edge from the room it is in to the room it opens, then run a DFS or BFS from room 0 and check that it reached all n rooms. Every room is entered at most once and every key is read once, so the search is O(n + k) time for n rooms and k keys, with O(n) extra space.
By Evin JohnPublished 6 min read
The problem in plain words
There are n rooms numbered 0 to n - 1. Room 0 is unlocked and the rest are locked. Inside each room is a list of keys, and a key numbered j opens room j. Once you enter a room you can take all of its keys, and you may move between rooms you have opened as often as you like. Return true if you can enter every room, false otherwise. Keys may repeat and a room may contain its own key.
| Keys in rooms 0, 1, 2, ... | Answer | Why |
|---|---|---|
| [2], [3], [1], [] | true | 0 gives 2, 2 gives 1, 1 gives 3. |
| [1, 2], [0], [0], [3] | false | The only key to room 3 is locked inside room 3. |
| [] | true | A single room that is already open. |
| [1], [] | true | Room 0 holds the only other key. |
Why it gets asked
It is a gentle graph question, often used early in a round or as a screening problem. The interviewer is checking whether you see that the story is a graph, whether you notice the edges are one-way, and whether your search marks rooms in a way that never enters a room twice or loops forever on keys that point back. Clean handling of a room containing its own key, or a key to room 0, shows care.
It also contrasts nicely with Number of Provinces. There the links go both ways and the question is how many groups exist. Here they are directed, and the question is whether one starting point reaches everything.
First idea: sweep until nothing changes
Keep a set of opened rooms, starting with room 0. Repeatedly go through every opened room and add the rooms its keys open. Stop when a full sweep adds nothing. It is easy to argue correct, but each sweep rereads keys you have already used, and a chain of rooms can force up to n sweeps, so the worst case is about O(n · (n + k)).
def can_visit_all_sweep(rooms):
opened = {0}
changed = True
while changed: # keep sweeping until a pass finds no new key
changed = False
for room in list(opened):
for key in rooms[room]:
if key not in opened:
opened.add(key)
changed = True
return len(opened) == len(rooms)One search from room 0
The repeated work disappears if each room's keys are read exactly once, at the moment you first get into it. That is a graph search. Keep a stack of rooms whose keys you have not yet collected, start it with room 0, and mark each room as visited when you first find its key. When the stack is empty, count the visited rooms.
def can_visit_all_rooms(rooms):
visited = [False] * len(rooms)
visited[0] = True
stack = [0]
count = 1
while stack:
room = stack.pop()
for key in rooms[room]:
if not visited[key]:
visited[key] = True # mark when the key is found, not when entering
count += 1
stack.append(key)
return count == len(rooms)Marking on discovery, not when a room is popped, keeps duplicate keys from pushing the same room twice. In the first layout the stack goes [0], then [2], then [1], then [3], then empty, with four rooms marked, so the answer is true. In the second, rooms 0, 1 and 2 are marked and room 3 never is.
function canVisitAllRooms(rooms) {
const visited = new Array(rooms.length).fill(false);
visited[0] = true;
const queue = [0];
for (let head = 0; head < queue.length; head++) { // a head index instead of shift()
for (const key of rooms[queue[head]]) {
if (!visited[key]) {
visited[key] = true;
queue.push(key);
}
}
}
return queue.length === rooms.length;
}Because a room enters the queue only once, the queue's final length is the number of rooms reached, so no separate counter is needed. DFS and BFS reach the same set; the order of visits is the only difference, and order does not matter here.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Sweep until no change | O(n · (n + k)) worst case | O(n) |
| DFS or BFS from room 0 | O(n + k) | O(n) |
Edge cases
- A single room: the answer is true.
- A room whose only key is to itself.
- Keys back to room 0, which is already open.
- The same key in several rooms, or twice in one room.
- An unreachable cycle: rooms 3 and 4 hold each other's keys, but nobody reachable holds either.
Mistakes
- Treating keys as two-way roads, which can report rooms as reachable when they are not.
- Forgetting to mark room 0 as visited before the search, so a key back to it re-adds it.
- Marking rooms when they are popped rather than pushed, and processing duplicates.
- Using shift() on a JavaScript array as the queue, which is linear per call in general.
- Returning true as soon as the stack empties, without comparing the count with n.
How to explain it out loud
Fictional example
- Candidate
- Each room is a node, and a key found in room a that opens room b is a one-way edge from a to b. The question is whether everything is reachable from room 0.
- Candidate
- I'll run a DFS with a stack, marking rooms as visited the moment I find their key so duplicates don't get pushed twice.
- Interviewer
- What does it cost?
- Candidate
- Each room is pushed at most once and each key is read once, so order of rooms plus keys. At the end I compare the number of visited rooms with n.
Related problems
Directed reachability leads naturally into ordering, covered in topological sort. For shortest distances rather than just reachability, BFS is the tool in Open the Lock and Shortest Path in Binary Matrix. Range Sum Query is the odd one out in this set, a data structure question rather than a graph one.
Working on it with Natively
Small graph questions like this one are good for practicing a clear spoken explanation. Natively can read the prompt from a screenshot on Mac or Windows and show an approach and code in its overlay, which you can compare with your own marking logic. If you talk through the solution in a mock round, the transcript it keeps helps you see whether you mentioned that the edges are one-way. See the AI interview assistant.
Questions people ask
How do you solve Keys and Rooms?
Run a DFS or BFS from room 0, treating each key as an edge to the room it opens. Mark rooms when their key is found and return whether the number marked equals n.
What is the time complexity of Keys and Rooms?
O(n + k) for n rooms and k keys in total, since each room is entered once and each key read once. Extra space is O(n).
Is Keys and Rooms a directed graph problem?
Yes. A key in room a opening room b is a one-way edge from a to b; it says nothing about getting from b back to a.
Should Keys and Rooms use DFS or BFS?
Either. Only the set of reachable rooms matters, not the order, so both give the same answer with the same cost.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
