← Snowflake Interview Insights
My first instinct was to BFS from each desk separately, which would have been a mess at scale.
Model the grid as a graph and run a multi-source BFS from all bathrooms simultaneously to compute the shortest distance to the nearest bathroom for every cell. Then, for each desk, read off the distance from the BFS result. This avoids running BFS from each desk individually, reducing time complexity.
Pro tip: Mention that multi-source BFS is optimal because it processes each cell once, and discuss how to handle unreachable desks (e.g., return -1 or infinity). Also, note that the grid can be large, so memory and time efficiency matter.
Confirm the grid dimensions, movement directions (4-directional), and what to return for desks with no reachable bathroom. Ask about input size to choose the right algorithm.
Initialize a queue with all bathroom cells and set their distance to 0. Use BFS to propagate distances to all reachable cells, updating distances as you go.
Use a 2D array to store distances, initialized to infinity. Process cells level by level, skipping walls and already visited cells. Use a queue for O(1) enqueue/dequeue.
After BFS, iterate through the grid and collect distances for all desk cells. If a desk remains at infinity, it's unreachable; decide on a sentinel value (e.g., -1).
State time complexity O(R*C) and space O(R*C). Discuss edge cases: no bathrooms, no desks, all walls, disconnected components.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.