Find nearest room; extend to two users
Company: Snapchat
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates competency in grid-based shortest-path algorithms, graph traversal, reachability analysis, and distance aggregation for multiple sources.
Nearest Meeting Room (BFS)
Constraints
- 1 <= m, n <= 1000
- grid[i][j] is one of 0 (empty), 1 (wall), 2 (meeting room)
- start is within bounds; if start is on a wall, return [-1, -1]
- If the start cell itself is a room (value 2), distance is 0 and that cell is returned
Examples
Input: ([[0,0,1,0],[0,2,1,0],[0,2,1,0]], [0,0])
Expected Output: [1, 1]
Explanation: From [0,0], BFS reaches room [1,1] at distance 2; the rooms in column 1 are the only reachable rooms (column 2 is a wall).
Input: ([[0,0,0],[0,1,0],[0,0,2]], [0,0])
Expected Output: [2, 2]
Explanation: The only room is at [2,2], reachable around the central wall at distance 4.
Hints
- Equal move cost means an unweighted graph: BFS, not Dijkstra, finds shortest distances.
- Mark cells visited the moment you enqueue them so you never revisit, and never step onto a wall (value 1).
- The first dequeued cell whose value is 2 is a nearest room — return immediately.
- Handle the edge cases: start on a wall, start already on a room, and no room reachable at all (return [-1, -1]).
Best Meeting Room for Two Users (Min Distance Sum)
Constraints
- 1 <= m, n <= 1000
- grid[i][j] is one of 0 (empty), 1 (wall), 2 (meeting room)
- s1 and s2 are within bounds (each may coincide with a room or with each other)
- Only rooms reachable by BOTH users are candidates
- Ties in total distance are broken by row-major order (smallest row, then column)
Examples
Input: ([[0,0,1,0],[0,2,1,0],[0,2,1,0]], [0,0], [2,0])
Expected Output: [[1, 1], 4]
Explanation: Room [1,1] is distance 2 from each user (total 4); room [2,1] is distance 3 + 1 = 4 as well but [1,1] wins on row-major order.
Input: ([[2,0,0,0,2],[0,0,0,0,0],[0,0,0,0,0]], [0,2], [2,2])
Expected Output: [[0, 0], 6]
Explanation: Both corner rooms give total 2 + 4 = 6; the tie is broken by row-major order, so [0,0] is returned.
Hints
- Run one BFS per user to get full distance maps; do not run a fresh search per room.
- Use -1 to mark unreachable cells so a single check (d1 != -1 and d2 != -1) enforces 'reachable by both'.
- After both BFS runs, scan every room cell once and minimize d1 + d2.
- If no room is reachable by both, the answer is [[-1, -1], -1] — initialize the best total to -1 and only update on a valid candidate.