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 bricks numbered 0 to n - 1 and snapped them together all afternoon, logging each snap as a pair like [2, 5].

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

Your task

Write countPieces(n, snaps). There are n bricks, numbered 0 to n - 1. Each [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 (like 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 joins 2 through 1). Bricks 4 and 5 form a second. Untouched brick 3 is a third.

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

The last two snaps add nothing: 2-0 closes a loop and 0-1 repeats. Bricks 0, 1, 2 are one piece and 3 another, so the answer is 2. Subtracting one piece per snap (4 bricks minus 4 snaps = 0) would be wrong, because snaps that repeat or close a loop do not join anything new.

Constraints

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

For each snap, scan all n bricks and give everything in the second brick's piece the first brick's label. Count distinct labels at the end.

That is 5,000 snaps × 2,000 bricks = 10 million steps. It works, but union-find handles each snap in nearly constant time. Building an adjacency list and running a depth-first search from each unvisited brick is also 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