DSA interview question
An electricity board must connect V substations with power lines at minimum total cost, given the cost of each possible line. Kruskal's algorithm sorts all candidate lines from cheapest to most expensive and adds each one unless it would close a loop, checking with a disjoint set union. When V − 1 lines have been added, the network is a minimum spanning tree.
Example: 4 substations, lines 0-1 (10), 0-2 (6), 0-3 (5), 1-3 (15), 2-3 (4) → 19.
long long kruskalMST(int V, vector<array<int, 3>> edges); // connected, undirected
Input (V, edges) | Output | Explanation |
|---|---|---|
(4, [[0,1,10],[0,2,6],[0,3,5],[1,3,15],[2,3,4]]) | 19 | 4 + 5 + 10; 0-2 (6) would close a loop |
(3, [[0,1,1],[1,2,1],[0,2,1]]) | 2 | Any two of the three |
(2, [[0,1,7],[0,1,3]]) | 3 | Parallel lines: take the cheaper one |
(5, [[0,1,1],[1,2,1],[2,3,1],[3,4,1],[0,4,100]]) | 4 | The expensive line isn't needed |
(1, []) | 0 |
(Confirm: the graph is connected; weights are non-negative; parallel edges are allowed.)
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