Walls and Gates
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 neededProblem
You are given an m x n grid called rooms. Each cell holds one of three kinds of values:
- -1 marks a **wall** or an obstacle that cannot be entered or passed through.
- 0 marks a **gate**.
- 2147483647 (which equals 2^31 - 1, used here as a stand-in for infinity) marks an **empty room**.
For every empty room, replace its value with the length of the shortest path to its nearest gate. You may move only **up, down, left, or right** between adjacent cells, and each step counts as distance 1. If an empty room cannot reach any gate (for example, it is sealed off by walls), leave its value as 2147483647.
Modify the grid in place. The function should also return the updated grid.
You should aim for a solution that runs in O(m * n) time rather than running a separate search from each empty room.
Examples
Constraints
- `m == rooms.length`
- `n == rooms[i].length`
- `1 <= m, n <= 250`
- Each `rooms[i][j]` is `-1`, `0`, or `2147483647`.
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.