Keys and Rooms

MediumGraphsdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

There are n rooms numbered 0 to n - 1. Room 0 is unlocked and every other room starts locked. Inside room i you find a set of keys rooms[i]; a key labeled k unlocks room k. Keys may be duplicated or open rooms you already visited. Starting in room 0, you may enter any room you hold a key for, collecting its keys, in any order. Return true if you can eventually enter **every** room, otherwise false.

Examples

Input: rooms = [[1],[2],[3],[]]
Output: true
Room 0 gives key 1, room 1 gives key 2, room 2 gives key 3.
Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
No reachable room contains key 2, so room 2 stays locked.

Constraints

  • 1 <= rooms.length <= 1000
  • 0 <= rooms[i].length <= 1000
  • The total number of keys is at most 3000
  • 0 <= rooms[i][j] < rooms.length

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems