Loose Pieces on the Table
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
n = 6 snaps = [[0, 1], [1, 2], [4, 5]]
3
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.
n = 4 snaps = [[0, 1], [1, 2], [2, 0], [0, 1]]
2
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- Hint 1
Start with every brick as its own piece:
npieces. How does the snap[0, 1]in the first example change the count? When does a snap not change it? - Hint 2
A snap lowers the count by one exactly when its two bricks were in different pieces. Otherwise it changes nothing.
- Hint 3
So you need to ask "already in the same piece?" and to merge two pieces, both fast. Give every piece one brick as its leader.
- Hint 4
Use union-find. Keep
parent[i], starting asi.find(x)follows parents up to the leader. For each snap, find both leaders; if they differ, point one at the other and subtract one from the count. Shortening paths asfindwalks them keeps it fast.
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.
How to solve it
Start with n pieces. Each snap either joins two different pieces, lowering the count by one, or joins bricks already connected, changing nothing. Union-find answers "already connected?" quickly by giving each piece a leader.
Trace the second example, n = 4, snaps 0-1, 1-2, 2-0, 0-1. Start: parent = [0, 1, 2, 3], pieces = 4.
- Snap 0-1. Leaders 0 and 1 differ. Set
parent[0] = 1. Pieces = 3. - Snap 1-2. Leaders 1 and 2 differ. Set
parent[1] = 2. Pieces = 2. - Snap 2-0.
find(2)is 2.find(0)walks 0 → 1 → 2, also 2. Same piece: skip. - Snap 0-1. Both leaders are 2. Skip.
Answer: 2. Brick 3 was its own leader throughout.
The line parent[x] = parent[parent[x]] makes each brick on the walk skip one level up, so over many calls the trees stay flat and find stays fast.
function countPieces(n, snaps) {
const parent = Array.from({ length: n }, (_, i) => i);
function find(x) {
while (parent[x] !== x) {
parent[x] = parent[parent[x]]; // shorten the path as we go
x = parent[x];
}
return x;
}
let pieces = n;
for (const [a, b] of snaps) {
const ra = find(a), rb = find(b);
if (ra !== rb) {
parent[ra] = rb; // merge two different pieces
pieces--;
}
}
return pieces;
}def count_pieces(n, snaps):
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # shorten the path as we go
x = parent[x]
return x
pieces = n
for a, b in snaps:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb # merge two different pieces
pieces -= 1
return piecesRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.