28 · Union-Find & Minimum Spanning Trees

#1319 Number of Operations to Make Network Connected

Mediumsolve on LeetCode ↗

frequently reported atAmazon

the problem

In plain words

n computers (0..n−1) are joined by ethernet cables connections[i] = [a, b]. In one operation you may unplug any cable and plug it between two computers. Return the minimum number of operations to connect all computers, or -1 if impossible.

in n = 4, connections = [[0,1],[0,2],[1,2]]

out 1

Move cable 1–2 to join computer 3.

in n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]

out 2

Two spare cables (1–2 and 1–3) bring in computers 4 and 5.

in n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]

out -1

Only 4 cables; 6 computers need at least 5.

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ connections.length ≤ min(n(n−1)/2, 10⁵)
  • No repeated connections

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #547
      Number of Provinces
      Mediumin Union-Find & MST
    2. #323
      Number of Connected Components in an Undirected Graph
      Mediumin Union-Find & MSTLeetCode Premium
    3. #684
      Redundant Connection
      Mediumin Union-Find & MST