Count the groups
Start with n groups, and lose one every time a merge actually joins two different groups. About 7 minutes.
Start with everyone alone, count down
How many friend circles are there in a class, given who's friends with whom? Everyone starts as a circle of one, so the count starts at n, the number of people.
Each merge of two different groups turns two circles into one, so the count goes down by 1. A merge between two people who are already in the same group changes nothing, so don't count it.
- groups
- 5
5 people, 5 groups of one. Start the count at 5.
The same question in many disguises
"How many friend circles?", "how many separate islands?", "how many clusters of servers?" all turn into this once you see them as a list of merges followed by a count.
For 5 people with merges 0-1, 1-2 and 3-4, you end with 2 groups: 0, 1, 2 together, and 3, 4 together.
parent = list(range(n))
def find(x):
while parent[x] != x:
x = parent[x]
return x
groups = n
for a, b in edges:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
groups -= 1
return groups4 people. Merges happen in this order: 0 with 1, 2 with 3, then 1 with 2. How many groups are left?
- A1
- B2
Show the answer
1. 0-1 leaves 3 groups, 2-3 leaves 2, and 1-2 joins those two into one.
Count the groups
There are n people, numbered 0 to n - 1, each starting in their own group. edges lists pairs [a, b] meaning a and b's groups are merged, in order. Return how many separate groups remain after every merge in edges.
n = 5, edges = [[0, 1], [1, 2], [3, 4]] → 2
1 ≤ n ≤ 1,000 · 0 ≤ edges.length ≤ 1,000 · edges[i] has two different node numbers, each 0 ≤ x < n