DSA interview question
A maps app stores roads as an undirected graph with non-negative travel times and must compute the fastest time from a source to every location. BFS no longer works because edges have different weights. Dijkstra's algorithm always expands the unsettled vertex with the smallest tentative distance. Since weights are non-negative, nothing found later can beat that distance, so it's final. A min-heap of (distance, vertex) pairs makes "smallest tentative distance" fast.
Example: 3 vertices, edges 0-1 (1), 1-2 (3), 0-2 (6), source 2 → [4, 3, 0].
vector<int> dijkstra(int V, const vector<array<int, 3>>& edges, int src); // undirected; -1 if unreachable
Input (V, edges, src) | Output | Explanation |
|---|---|---|
(3, [[0,1,1],[1,2,3],[0,2,6]], 2) | [4, 3, 0] | 2→1→0 beats 2→0 |
(4, [[0,1,4],[0,2,1],[2,1,2],[1,3,1],[2,3,5]], 0) | [0, 3, 1, 4] | |
(2, [[0,1,9]], 0) | [0, 9] | |
(3, [[0,1,2]], 0) | [0, 2, -1] | 2 is unreachable |
(1, [], 0) | [0] |
(Confirm: weights are non-negative; edges are undirected; 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