DSA interview question
A routing team is choosing how to implement Dijkstra for a directed road graph with non-negative weights, and wants to understand why a priority queue is the standard choice. Implement the three classic versions and confirm they agree:
The heap versions pick the next vertex in O(log V) instead of O(V), which matters for sparse graphs.
Example: 5 vertices, edges 0→1 (10), 0→2 (3), 2→1 (4), 1→3 (2), 2→3 (8), 3→4 (7), source 0 → [0, 7, 3, 9, 16].
vector<long long> dijkstraArray(int V, const vector<vector<pair<int, int>>>& adj, int src); // O(V^2)
vector<long long> dijkstraSet(int V, const vector<vector<pair<int, int>>>& adj, int src); // O(E log V)
vector<long long> dijkstraHeap(int V, const vector<vector<pair<int, int>>>& adj, int src); // O(E log V)
Input (V, directed edges, src) | Output (all three agree) | Explanation |
|---|---|---|
(5, [[0,1,10],[0,2,3],[2,1,4],[1,3,2],[2,3,8],[3,4,7]], 0) | [0, 7, 3, 9, 16] | 1 via 2 costs 7, not 10 |
(3, [[0,1,1],[1,2,1],[0,2,5]], 0) | [0, 1, 2] | |
(4, [[0,1,1],[0,2,1],[1,3,1],[2,3,1]], 0) | [0, 1, 1, 2] | |
(3, [[1,0,1]], 0) | [0, -1, -1] | Edges point the wrong way |
(1, [], 0) | [0] |
(Confirm: edges are directed with non-negative weights; unreachable vertices print −1.)
priority_queue doesn't, hence lazy deletion or set.)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