Fewest Cable Moves to Connect Every Machine in a Rack
Last updated: November 29, 2026
Quick Overview
A rack has n machines and a list of cables, each joining two machines. You may unplug any cable and replug it between any two machines. Return the minimum number of moves to make every machine reachable from every other, or -1 if it is impossible.
0
0
0 solved
A rack has n machines and a list of cables, each joining two machines. You may unplug any cable and replug it between any two machines. Return the minimum number of moves to make every machine reachable from every other, or -1 if it is impossible.
This appears in Google style online assessments framed around datacenter hardware. The interviewer is checking two insights: a spanning connection needs at least n - 1 cables, and once that holds the answer is simply the number of components minus one, because spare cables live inside cycles.
What the Interviewer Expects
- Rejects the case with fewer than n - 1 cables up front
- Counts components with union-find
- Explains why redundant cables always exist when the count check passes
- Returns components minus one
- Keeps the code linear in practice
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Return the actual list of moves, not just the count.
- What if each move has a cost based on rack distance?
- How does the answer change if some machines must not be touched?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
nmachines0..n-1, listcablesof pairs. - A move takes an existing cable and reconnects it anywhere.
- Output: minimum moves, or -1 if connection is impossible.
- No new cables can be ...
High-Level Design
A connected network of n machines needs at least n - 1 cables, so if we have fewer the answer is -1 immediately. Otherwise, count connected components c. To merge c components we need exactly c - 1 br...