Number of Operations to Make Network Connected

MediumGraphsunion find

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

There are n computers labeled 0 to n - 1, and connections[i] = [a, b] is a cable directly linking computers a and b. Any computer can reach any other computer it is linked to through a chain of cables. In one operation you may unplug an existing cable and plug it in between any two computers that are not currently directly linked. Return the minimum number of operations needed so that every computer can reach every other computer. If it is impossible, return -1. There are no duplicate cables and no cable links a computer to itself.

Examples

Input: n = 5, connections = [[0,1],[1,2],[0,2],[3,4]]
Output: 1
The groups are `{0,1,2}` and `{3,4}`. The cable `[0,2]` is redundant, so move it to link the two groups: one operation.
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
Output: -1
Connecting 6 computers needs at least 5 cables, but only 4 exist.

Constraints

  • 1 <= n <= 10^5
  • 0 <= connections.length <= min(n * (n - 1) / 2, 10^5)
  • `connections[i].length == 2`
  • 0 <= a, b < n, a != b, no repeated cables

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More union find problems