Number of Operations to Make Network Connected

Medium · Graphs · Depth-First Search · Breadth-First Search · Union Find · Graph

Problem

There are n computers numbered 0 to n - 1, joined by cables: connections[i] = [a, b] is a cable between computers a and b. Two computers can talk if a chain of cables joins them.

In one operation you may unplug any cable and plug it in between two computers that are not directly connected. Return the fewest operations needed so that every computer can talk to every other, or -1 if that is impossible.

Examples

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

The cable 1-2 is spare; moving it to join the piece {3, 4} to the rest connects everything.

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

Four computers need at least three cables, and only two exist.

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

Every computer can already reach every other.

Constraints

Approaches

Follow-up

Only the count of pieces matters here, so any way of counting connected components works: union-find, DFS or BFS. Union-find also counts the spare cables on the way (each cable whose ends were already together), and it handles cables arriving one at a time, which a DFS would have to redo from scratch.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…