Loose Pieces on the Table

Easyunion-findAlso known as Number of Connected Components in an Undirected Graph

Your little brother tipped out a box of building bricks numbered 0 to n - 1 and spent the afternoon snapping them together. He kept a log: each line says which two bricks he snapped together, like [2, 5].

Before tidying up, you want to know how many separate pieces are lying on the table. A piece is any group of bricks held together, directly or through other bricks. A brick nobody touched is a piece on its own.

Your task

Write countPieces(n, snaps). There are n bricks, numbered 0 to n - 1. Each entry [a, b] in snaps means bricks a and b were snapped together. Return the number of separate pieces.

The same pair can appear more than once, and snaps can close loops (for example 0-1, 1-2, 2-0). Neither changes which bricks are joined.

countPieces(n: int, snaps: int[][]) → int

Examples

Example 1
Input
n = 6
snaps = [[0, 1], [1, 2], [4, 5]]
Output
3
Why

Bricks 0, 1 and 2 form one piece (0 is joined to 2 through 1). Bricks 4 and 5 form a second. Brick 3 was never touched, so it is a third piece.

Example 2
Input
n = 4
snaps = [[0, 1], [1, 2], [2, 0], [0, 1]]
Output
2
Why

Four snaps, but the last two add nothing new: 2-0 closes a loop and 0-1 repeats. Bricks 0, 1, 2 are one piece and brick 3 is another, so 2. Computing 4 bricks minus 4 snaps = 0 would be wrong.

Constraints

  • 1 ≤ n ≤ 2,000
  • 0 ≤ snaps.length ≤ 5,000
  • 0 ≤ a, b < n and a ≠ b
Start with brute force

For each snap, relabel: give every brick in the second brick's piece the first brick's label by scanning all n bricks. Count the distinct labels at the end.

That is n work per snap, so 5,000 snaps × 2,000 bricks = 10 million steps. It works, but union-find does each snap in nearly constant time. Building the full adjacency list and running a depth-first search from each unvisited brick is also fast and perfectly fine here.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code