InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Keys and Rooms

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug