There are n rooms, numbered 0 to n − 1. Room 0 is open and every other room starts locked. Each room may contain some keys, and a key with number j unlocks room j. You can take every key you find and use it any time later.
You are given rooms, where rooms[i] lists the keys inside room i. Return true if you can get into every room, and false if some room stays locked.
Example 1
Input: rooms = [[1, 2], [3], [], [2]] Output: true Why: 0 opens 1 and 2, then 1 opens 3
2 more examples and the constraints
Example 2
Input: rooms = [[2], [0], [1], [3]] Output: false Why: the only key to room 3 is inside room 3
Example 3
Input: rooms = [[], [0]] Output: false Why: room 0 holds no keys, so you never leave it
Constraints
- 2 ≤ n ≤ 1,000
- At most 3,000 keys in total, and at least 1
- Every key is a room number from 0 to n − 1, and no room lists the same key twice
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sweep until nothing changesO(n · (n + k))
- Depth-first search with a stackO(n + k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 rooms in a reverse chain | Verdict |
|---|---|---|---|
| Sweep until nothing changes | O(n · (n + k)) | Passes here, but re-reads rooms | |
| Depth-first search with a stack | O(n + k) | Best; every room read once |
n = number of rooms, k = total number of keys.
Edge cases to test
- Room 0 is empty. [[], [0]] is false: you cannot leave room 0.
- Key locked inside its own room. A room whose only key is in itself can never be opened.
- Keys to rooms already open. Keys to room 0 or to a visited room must be skipped, or the search loops.
- Long chain. Room 0 opens 1, which opens 2, and so on for 1,000 rooms: deep recursion can overflow, a stack cannot.
Common mistakes
- Marking a room only when it is popped, so the same room can be pushed many times.
- Starting with room 0 not marked, so a key back to room 0 sends the search round again.
- Stopping after one sweep in the first approach, missing keys found later in that sweep.
How to talk through it
- 1Clarify. Can a key be reused? Can a room hold a key to itself or to room 0?
- 2Give the simple version. Sweep until nothing new opens; say why it can take n sweeps.
- 3Reframe as a graph. Rooms are nodes, keys are directed edges, and the question is reachability from 0.
- 4Code the stack search. Mark when you push, pop to read keys, and count the rooms you reached.
- 5Test out loud. Run an empty room 0, a self-locked room and a long chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?