InterviewPrepKit

Home / Coding / Graphs

Keys and Rooms

medium Original β†—
Solving tips
  • Reframe it as plain reachability: rooms are nodes, a key j in room i is a directed edge i->j, so the question is 'are all nodes reachable from room 0?'
  • DFS or BFS from room 0 collecting keys, then return len(visited) == len(rooms); O(V+E) time, O(V) space.
  • The only bookkeeping that matters is a visited set to avoid infinite loops on cyclic keys (a room listing its own label or mutual keys).
  • Pitfall: don't conclude True just because every room label appears as a key somewhere; unreachable clusters can still name each other.

Problem

There are n rooms labeled 0 to n - 1. You start in room 0, and every other room is locked. Each room i contains a list rooms[i] of keys, where each key is the label of a room it unlocks.

Return True if you can enter all n rooms, False otherwise.

You may pick up keys from a room the first time you enter it and use them to open other rooms; keys can be used any number of times.

Examples

  • rooms = [[1],[2],[3],[]] β†’ True β€” 0 gives key 1, 1 gives key 2, 2 gives key 3; all four visited.
  • rooms = [[1,3],[3,0,1],[2],[0]] β†’ False β€” room 2 is never referenced by any key you can reach, so it stays locked.
  • rooms = [[1],[],[0,2]] β†’ False β€” from 0 you get key 1, room 1 is empty, and nothing ever hands you key 2.

Constraints

  • n == len(rooms), 2 <= n <= 1000.
  • 0 <= sum(len(rooms[i])) <= 3000.
  • Keys are valid room labels; a room may list duplicate keys and may list its own label.

Think about it first

Hint 1 Rooms are nodes; a key j in room i is a directed edge i β†’ j. The question "can I open every room?" is "is every node reachable from room 0?" β€” a plain reachability traversal.
Hint 2 DFS or BFS from room 0, collecting keys (i.e. following edges) and marking rooms visited so you don't loop forever on cyclic keys. At the end, compare the number of visited rooms to n.
Hint 3 The only bookkeeping that matters is a visited set: enter a room only if you haven't already. Both DFS (stack/recursion) and BFS (queue) work identically here; the answer is len(visited) == n.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.