DSA interview question
An office has n computers joined by some network cables. An IT technician can unplug any cable and reconnect it between two other computers. What's the minimum number of such moves to connect every computer, or −1 if it's impossible? Connecting n computers needs at least n − 1 cables, so with fewer it's impossible. Otherwise, redundant cables (those inside an already-connected group) can be moved, and each move links one more group. The answer is (number of components) − 1, which union-find counts.
Example: n = 4, cables 0-1, 0-2, 1-2 → 1 (move the redundant 1-2 cable to computer 3).
int makeConnected(int n, const vector<pair<int, int>>& connections);
Input (n, connections) | Output | Explanation |
|---|---|---|
(4, [[0,1],[0,2],[1,2]]) | 1 | Two components; one spare cable |
(6, [[0,1],[0,2],[0,3],[1,2],[1,3]]) | 2 | Components {0,1,2,3}, {4}, {5} |
(6, [[0,1],[0,2],[0,3],[1,2]]) | -1 | Only 4 cables for 6 computers |
(3, [[0,1],[1,2]]) | 0 | Already connected |
(1, []) | 0 |
(Confirm: cables are undirected with no duplicates; a move relocates one existing cable.)
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