Number of Operations to Make Network Connected
Problem Statement
There are n computers, numbered 0 to n − 1. Some pairs are joined by a cable. You get the cables as connections, where connections[i] = [a, b] joins computers a and b directly. Two computers can talk if a chain of cables joins them.
You can unplug any cable and plug it into a different pair of computers. Return the minimum number of moves (cables unplugged and plugged in again) so that every computer can talk to every other one. If it cannot be done, return -1.
n, the number of computers, and connections, the list of cables.
The minimum number of cable moves, or -1 if it is not possible.
Computers 0, 1 and 2 are linked, and computer 3 is alone. Move cable 1–2 (it closes a loop, so nothing breaks) to join 3 to the group.
Computers 0 to 3 form one group, and 4 and 5 are alone. The spare cables 1–2 and 1–3 close loops, so each can join one of the lone computers: 2 moves.
Connecting 6 computers needs at least 5 cables, and there are only 4.
- • 1 ≤ n ≤ 10^5
- • 1 ≤ connections.length ≤ min(n · (n − 1) / 2, 10^5)
- • 0 ≤ aᵢ, bᵢ < n
- • aᵢ ≠ bᵢ
- • No two computers are connected by more than one cable.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Keep a group label per computer; each join renames one whole group
Union each cable; every successful union removes one group; the answer is groups − 1
Give every computer a group label, starting with its own number. For each cable whose ends have different labels, rename every computer with one label to the other label, and count one fewer group. Every join costs a full pass over all n computers.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Union-Find (DSU) translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.