oneby7

Graphs Union-find

463. Number of Operations to Make Network Connected

Medium

You have n computers, numbered from 0 to n - 1. Each pair [a, b] in connections is a cable that joins computers a and b directly.

A network is a group of computers in which every computer can reach every other one through cables, and that no cable joins to a computer outside the group. A computer with no cable is a network on its own.

In one move, you unplug any cable and plug it in again between two computers that have no cable between them. You cannot add new cables. Return the fewest moves that put all n computers in one network. If that cannot be done, return -1.

Example 1

01234567

Input: n = 8 connections = [[0, 1], [1, 2], [2, 0], [3, 4], [4, 5], [5, 3], [2, 3]]

Output: 2

Explanation: Computers 0 to 5 form one network, and computers 6 and 7 are networks on their own. One move takes [2,0] to join 0 and 6, since 0 and 2 stay joined through 1. A second move takes [5,3] to join 3 and 7.

Example 2

01234

Input: n = 5, connections = [[0, 1], [1, 2], [2, 0]]

Output: -1

Explanation: Joining 5 computers takes at least 4 cables, and there are only 3.

Example 3

0123

Input: n = 4, connections = [[3, 0], [0, 2], [2, 1]]

Output: 0

Explanation: The cables already join all four computers, so no move is needed.

Check your understanding

Work out the answer for this input before you write any code.

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

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ connections.length ≤ 2 × 105
  • connections[i].length == 2
  • 0 ≤ ai, bi < n
  • ai ≠ bi
  • No cable appears twice: [a, b] and [b, a] are the same cable.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.