677. Keys and Locked Rooms

A treasure vault has n rooms numbered 0 to n-1. Room 0 is open and all the other rooms are locked. Inside room i you find the keys listed in rooms[i]; a key with value k opens room k, and keys are never used up, so you may reuse them freely. You may walk into any room whose key you hold.

Return true if you can eventually enter every room, otherwise false. A room may contain no keys, repeated keys, or a key to itself. Plan for up to a hundred thousand rooms, so use an explicit stack or queue rather than deep recursion. The expected cost is O(n + k) time, where k is the total number of keys, and O(n) space.

Example 1

Input:
rooms = [[2],[],[1,3],[0]]
Output:
true
Explanation:

Room 0 holds the key to room 2, room 2 holds keys to rooms 1 and 3, so all four rooms can be entered.

Example 2

Input:
rooms = [[1],[0],[],[2]]
Output:
false
Explanation:

Rooms 0 and 1 only contain keys to each other; nobody holds the key to room 2 or room 3, so they stay locked.

Constraints

1 ≤ n ≤ 100000

0 ≤ total number of keys ≤ 200000

0 ≤ every key < n

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 200 msC++ 50 msJava 100 msJavaScript 100 msTypeScript 100 ms

Expected complexity

Time
O(n + k)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…