download

Edges arrive one by one. How many groups are there now?

Algorithms~20 minReviewed 1 Nov 2026Free · No sign-in

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.

"PYTHON"
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.

"CODE · PYTHON"
def count_groups(n, edges):
    ...
Show hints (3)
  1. "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?

  2. "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.

  3. "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.

"SOLUTION · PYTHON"
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)])
"OUTPUT"
(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:

edgerootswhat happensgroups
(0, 1)0, 11 goes under 05
(2, 3)2, 33 goes under 24
(1, 3)0, 22 goes under 03
(0, 2)0, 0same group: skip3
(4, 4)4, 4same user twice: skip3
(4, 5)4, 55 goes under 42

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 every parent entry is a root. At the end, parent is [0, 0, 0, 2, 4, 4]: that gives 3 groups instead of 2. Count the distinct find(x) values instead.
  • Comparing parent[a] == parent[b] instead of the roots. After the third edge, parent[3] is 2 but parent[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 recursive find(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 →

Original OfferVibe question. Topic idea from Crushing the Technical Interview (Keith Henning, 2025); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.