DSA Factory
Free lessonsUnion-find · Stage 0 · Groups that merge · Step 3

Largest group

Track each root's group size alongside parent, and add sizes together whenever two groups merge. About 8 minutes.

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))
Quick check

Groups of 1, 1 and 2 people all merge into one group. How big is it?

  1. A4
  2. B2
Show the answer

4. 1 + 1 + 2 = 4. Merging adds the sizes together.

Your problem

Largest group

There are n people, numbered 0 to n - 1, each starting alone. edges lists pairs [a, b] meaning a and b's groups are merged, in order. Return the size of the largest group once every merge in edges has happened.

Example
n = 5, edges = [[0, 1], [1, 2], [3, 4]] → 3

1 ≤ n ≤ 1,000 · 0 ≤ edges.length ≤ 1,000 · edges[i] has two different node numbers, each 0 ≤ x < n

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding