Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

The leader keeps the headcount

Now you also want to know how big each group is. Give every person a size, starting at 1: a group of one.

Only the leader's size matters. When two groups merge, the new leader adds the other leader's size to its own. The old leader's size is simply never looked at again, like a club secretary handing over the membership list.

Everyone starts at 1: a group of one.
Only the leader's size: is kept up to date.
5 people, merged 0–1, 1–2, 3–4 · each leader shows its group size
0111213141

Everyone is a group of 1.

Move 1 of 5

Sizes add up, never overwrite

When groups of 2 and 3 merge, the new group has 5 people. The sizes add. When every merge is done, the biggest size held by any leader is the answer.

For 5 people with merges 0-1, 1-2 and 3-4, the leaders hold sizes 3 and 2, so the answer is 3.

Merging adds sizes: the new leader takes both.
In code
parent = list(range(n))
size = [1] * n
def find(x):
    while parent[x] != x:
        x = parent[x]
    return x
for a, b in edges:
    ra, rb = find(a), find(b)
    if ra != rb:
        parent[ra] = rb
        size[rb] += size[ra]
return max(size[find(i)] for i in range(n))