DSA interview question
A city grid marks hospitals with 1 and ordinary blocks with 0. For planning ambulance coverage, every block needs its distance to the nearest hospital, moving up, down, left or right. Running a BFS from every block is O((R·C)²). Reverse the viewpoint instead: start a single BFS from all hospitals at once (multi-source). The first time the BFS reaches a block is its distance to the nearest hospital.
Example: [[0,1,1,0], [1,1,0,0], [0,0,1,1]] → [[1,0,0,1], [0,0,1,1], [1,1,0,0]].
vector<vector<int>> nearest(const vector<vector<int>>& grid); // at least one 1 exists
| Input | Output | Explanation |
|---|---|---|
[[0,1,1,0],[1,1,0,0],[0,0,1,1]] | [[1,0,0,1],[0,0,1,1],[1,1,0,0]] | |
[[1,0,1],[1,1,0],[1,0,0]] | [[0,1,0],[0,0,1],[0,1,2]] | |
[[0,0],[0,1]] | [[2,1],[1,0]] | |
[[1,0,0,0]] | [[0,1,2,3]] | |
[[1]] | [[0]] |
(Confirm: distance is the number of 4-directional steps; the grid has at least one 1.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in