Magicsheet logo

Number of Operations to Make Network Connected

Medium
97.6%
Updated 6/1/2025

Number of Operations to Make Network Connected

What is this problem about?

The Number of Operations to Make Network Connected problem gives you n computers and a list of connections (edges). In one operation, you can remove any existing connection and add it elsewhere. Find the minimum operations needed to connect all computers. If impossible, return -1. This coding problem reduces to counting connected components and extra (redundant) edges.

Why is this asked in interviews?

Microsoft, Meta, Amazon, Google, and Bloomberg ask this because it tests a key graph insight: to connect k disconnected components, you need k-1 edges. If you have at least k-1 redundant edges (edges in cycles), it's solvable. The union find, BFS, graph, and DFS interview pattern is directly applied with a clean mathematical conclusion.

Algorithmic pattern used

Union-Find to count components and redundant edges. Process all edges: if two endpoints are already in the same component, it's a redundant edge (increment redundant count). Otherwise, union them (decrement component count). After processing, if redundant >= components - 1, return components - 1. Otherwise return -1.

Example explanation

n=6, connections=[(0,1),(0,2),(3,4),(4,5)].

  • Union(0,1): components=5. Union(0,2): components=4. Union(3,4): components=3. Union(4,5): components=2.
  • Redundant=0. Components=2. Need 1 edge. Redundant(0) ≥ 1? No → return -1.

n=6, connections=[(0,1),(0,2),(0,3),(1,2),(3,4),(4,5)].

  • (1,2) is redundant (0,1,2 already connected). Redundant=1. Final components=3.
  • Need 2 edges but only 1 redundant → -1.

Hmm, let me use: n=4, connections=[(0,1),(0,2),(1,2),(1,3)]:

  • (1,2) redundant. Components: {0,1,2,3} = 1. Need 0 ops → 0.

Common mistakes candidates make

  • Not checking the impossible case early (need at least n-1 edges total).
  • Counting all edges as potentially redundant (only cycle-creating edges are redundant).
  • Returning component_count instead of component_count - 1.
  • Not initializing each node as its own component.

Interview preparation tip

This problem elegantly combines two graph concepts: connected components (Union-Find) and redundant edges (cycle detection). The formula: minimum connections to make a graph connected = number_of_components - 1. Always check feasibility first: if total_edges < n-1, impossible. Practice similar "minimum spanning tree" connectivity problems — they share the same component-counting logic.

Similar Questions