Skip to content
Decoder

Keys and Rooms

Medium

Problem

There are n locked rooms numbered 0 to n - 1, except room 0, which is open. rooms[i] lists the keys you find inside room i; a key with number j opens room j. You may enter rooms in any order once you hold their key. Return true if you can visit every room, and false otherwise.

Example 1

Input
rooms = [[1], [2], [3], []]
Output
true
Why
0 → 1 → 2 → 3

Example 2

Input
rooms = [[1, 3], [3, 0, 1], [2], [0]]
Output
false
Why
nobody holds the key to room 2

Constraints

  • 2 <= n <= 1000
  • 0 <= rooms[i].length <= 1000
  • The total number of keys across all rooms is at most 3000
  • Every key is a valid room number

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.