DSA interview question
A metro map is an undirected graph where every hop between adjacent stations takes the same time. For a given source station, the app shows the minimum number of hops to every station, or −1 if a station can't be reached. With equal edge weights, BFS is the shortest-path algorithm. It discovers vertices in order of their distance, so the first time a station is reached, its distance is final.
Example: 9 stations, source 0 → [0, 1, 2, 1, 2, 3, 3, 4, 4].
vector<int> shortestPath(int n, const vector<pair<int, int>>& edges, int src); // -1 if unreachable
Input (n, edges, src) | Output | Explanation |
|---|---|---|
(9, [[0,1],[0,3],[3,4],[4,5],[5,6],[1,2],[2,6],[6,7],[7,8],[6,8]], 0) | [0, 1, 2, 1, 2, 3, 3, 4, 4] | |
(5, [[0,1],[0,2],[1,3],[2,3],[3,4]], 4) | [3, 2, 2, 1, 0] | |
(4, [[0,1],[1,2]], 0) | [0, 1, 2, -1] | 3 is unreachable |
(3, [], 1) | [-1, 0, -1] | |
(1, [], 0) | [0] |
(Confirm: undirected edges, all of weight 1; unreachable vertices get −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