Edges arrive one by one. How many groups are there now?
Question
A chat app has 6 users, numbered 0 to 5. Friendships arrive one at a time. Two users are in the same group if a chain of friendships links them.
Write count_groups(n, edges). After each friendship, print it and the number of groups. Don't rescan the whole graph after every event.
count_groups(6, [(0, 1), (2, 3), (1, 3), (0, 2), (4, 4), (4, 5)])
The counts should be 5, 4, 3, 3, 3, 2.
def count_groups(n, edges): ...
Show hints (3)
- "START COUNTING"
Every user starts as a group of one, so there are 6 groups. Which friendships make the count go down, and by how much?
- "ONE LEADER EACH"
Give each group one leader, its root. Follow
parent[x]until you reach a user who is their own parent. Two users share a group when they reach the same root. - "JOIN THE ROOTS"
For a friendship (a, b), find both roots. Equal roots: nothing changes. Different roots: point one at the other and subtract 1 from the count.
Show checked explanation
Use union-find. The count starts at n, one group per user. For each friendship, find the root of both users. If the roots differ, link one under the other and subtract 1. If they are the same, nothing changes. With union by size and path compression, each step costs almost O(1), amortized.
def count_groups(n, edges): parent, size = list(range(n)), [1] * n def find(x): if parent[x] != x: parent[x] = find(parent[x]) # path compression return parent[x] groups = n for a, b in edges: ra, rb = find(a), find(b) if ra != rb: if size[ra] < size[rb]: ra, rb = rb, ra # attach the smaller group parent[rb] = ra size[ra] += size[rb] groups -= 1 print((a, b), groups) count_groups(6, [(0, 1), (2, 3), (1, 3), (0, 2), (4, 4), (4, 5)])
(0, 1) 5 (2, 3) 4 (1, 3) 3 (0, 2) 3 (4, 4) 3 (4, 5) 2
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Here is the trace:
| edge | roots | what happens | groups |
|---|---|---|---|
| (0, 1) | 0, 1 | 1 goes under 0 | 5 |
| (2, 3) | 2, 3 | 3 goes under 2 | 4 |
| (1, 3) | 0, 2 | 2 goes under 0 | 3 |
| (0, 2) | 0, 0 | same group: skip | 3 |
| (4, 4) | 4, 4 | same user twice: skip | 3 |
| (4, 5) | 4, 5 | 5 goes under 4 | 2 |
The final groups are {0, 1, 2, 3} and {4, 5}. Each join of two different groups drops the count by exactly 1, so the count is always n minus the number of joins.
Look at (0, 2). Users 0 and 2 had no direct friendship, but the chain 0, 1, 3, 2 already linked them. Union-find sees this at once: both have root 0.
After the third edge, parent[3] is 2 and parent[2] is 0, so 3 needs two steps to reach its root. On the next lookup, path compression fixes that: find(3) sets parent[3] to 0. Only the shortcut changes, not the group.
Union by size attaches the smaller tree under the bigger one. A user moves one level deeper only when its group at least doubles, so no path is longer than log₂ n steps. That keeps the recursive find far from the recursion limit. Path compression shortens paths further. With both, the amortized cost per operation is practically constant. The bound uses α(n), the inverse Ackermann function, which grows extremely slowly. A single find can still take O(log n) steps.
Common mistakes
- Counting groups as
len(set(parent)). Not everyparententry is a root. At the end,parentis[0, 0, 0, 2, 4, 4]: that gives 3 groups instead of 2. Count the distinctfind(x)values instead. - Comparing
parent[a] == parent[b]instead of the roots. After the third edge,parent[3]is 2 butparent[0]is 0. An edge (0, 3) would look new and drop the count to 2. - Skipping union by size and path compression. With
parent[ra] = rb, edges (0, 1), (1, 2), (2, 3) and so on build one long chain. For 2,000 users, a recursivefind(0)passes the recursion limit of 1000. - Using a root as a stable group id. The root of {2, 3} was 2; after the next join it is 0. Keep your own ids if the outside world needs them.
Follow-up questions
- "Which friendship was redundant?" The first edge whose two users already share a root. Here that is (0, 2). In the classic "redundant connection" task, a tree gets one extra edge, and this finds it.
- "Now friendships can also end. Does union-find still work?" Not directly. Union-find can join groups but not split them. Its parent links are shortcuts, not real friendships. If (1, 3) ends, the skipped edge (0, 2) now holds the group together. The simple fix is to rebuild from the remaining edges in O(n + m) time.
- "Why not just run BFS after each friendship?" Each BFS costs O(n + m), so m events cost O(m·(n + m)). Union-find answers each event in almost constant time. BFS is fine for one question on a fixed graph.
What a strong answer covers
Starts the count at n and subtracts 1 only when two different roots join. Uses union by size and path compression, and says the bound is amortized. Knows union-find can't remove edges.
Open in interactive practice deck →