We're live on Product Hunt today! Use code PRODUCTHUNT26 for 20% off. Upvote us ↑
DSA Trainer
← All problems
PremiumGraph TraversalMedium

Keys and Rooms

Asked at:AmazonGoogle

There are n rooms numbered 0 to n-1. Room 0 is unlocked. Each room contains a list of keys to other rooms. Starting from room 0, determine if you can visit all rooms.

This is a premium problem.

Unlock Keys and Rooms with both full courses, DSA and System Design, and every other premium problem.

Problem

There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. When you visit a room, you may find a set of distinct keys in it. Return true if you can visit all the rooms, or false otherwise.

Input

A list of lists `rooms` where `rooms[i]` is the list of keys found in room i.

Output

`true` if you can visit all rooms, `false` otherwise.

Examples

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

Output: true

Visit room 0, get key 1. Visit room 1, get key 2. Visit room 2, get key 3. Visit room 3.

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

Output: false

Room 2 can never be accessed — none of the reachable rooms contain key 2.

The brute-force approach

BFS/DFS from room 0. Collect all keys found. Repeat until no new rooms can be unlocked. Check if all rooms were visited.

visited = {0}
stack = [0]
while stack:
    room = stack.pop()
    for key in rooms[room]:
        if key not in visited:
            visited.add(key)
            stack.append(key)
return len(visited) == len(rooms)

O(n + k) where k is total keys — this is already the optimal approach.

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

Spotting the pattern

This is a Graph Traversal problem. The key question to ask yourself:

This is a reachability problem starting from room 0. What data structure tells you which rooms you've already visited, and why does that prevent infinite loops?

Answering that is where it clicks, and it's exactly what the guided walkthrough below builds with you: the pattern reasoning, a progressive hint ladder that never spoils the answer, a row-by-row dry run, the optimized solution, and an in-browser editor to run your code against real test cases.

Premium

Unlock the full guided solution

The Graph Traversal walkthrough for Keys and Rooms: the progressive hint ladder, a row-by-row dry run, the optimized code, and an in-browser runner, plus both full courses, DSA and System Design, and every other premium problem.

Already finished Big-O and Hash Maps free? This picks up right where the path leads: same format, harder patterns, the ones that show up in every FAANG-style screen.

What you get

  • The full DSA course: concept lessons, drills, graded tests, and cold-read capstones for every pattern
  • The full System Design course: 20 building-block units for the design round, included at no extra cost
  • Stop going blank on algorithm problems. The hint ladder walks you to the answer without spoiling it.
  • Actually internalize the trace: dry runs walk state row by row so it clicks before you write a line
  • Know when to reach for each pattern. Every problem names the trigger so you spot it next time.
  • Write and run JS or Python in the browser with real test cases on every problem
  • Access every new problem, unit, and pattern guide as they ship weekly
B
Big_Wolverine_7575Founding Member· unprompted on Reddit

“This app finally made it click. I tried NeetCode, CTCI, and YouTube for years and still couldn't solve Two Sum. The beginner mental models for the patterns are genuinely so helpful. THANK YOU.

Full access · both courses

Full access

$49 / year

or $9 / month

Now includes a C++ runner alongside JavaScript and Python.

LeetCode Premium is $159/year and doesn't teach you anything.

Less than one Udemy course, with guided problems instead of passive lectures.

One extra month of job searching costs more than a full year here.

  • Both courses, every unit: DSA + System Design
  • All 150 problems across 33 patterns, plus every new one
  • New problems and units weekly
  • Cancel anytime

Cancel anytime. Not useful within 7 days? Email for a full refund. Secured by Stripe.