Keys and Rooms

Medium

This is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.

Question

You're given a numbered set of storage bins. Bin 0 starts unsealed. Every other bin starts sealed.

Opening a bin reveals a list of numbers. Each number tells you another bin that gets unsealed. The same number can show up more than once. A bin's list can even contain its own number.

Return whether every bin in the set can eventually be unsealed.

Input: rooms = [[1], [2], [3], []]

Output: True

Bin 0 reveals bin 1. Bin 1 reveals bin 2. Bin 2 reveals bin 3. All four bins end up unsealed.

Input: rooms = [[1, 3], [3, 0, 1], [2], []]

Output: False

Bin 0 unseals bin 1 and bin 3. Bin 1's list only points back to bin 3, bin 0, and itself. That means nothing new gets unsealed. Bin 2's list only mentions itself. No other bin ever reveals it. Bin 2 stays sealed forever.

Input: rooms = [[0, 1], [2], []]

Output: True

Bin 0's list includes its own number. That changes nothing because bin 0 is already unsealed. Bin 0 also reveals bin 1, and bin 1 reveals bin 2.

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

Can every bin be unsealed for this input? rooms = [[1], [], [3], []]
No
Yes
Yes, since bin 0 is already unsealed
Not enough information

Remember to understand the problem and plan your approach before you start coding.