Skip to content
BytePatterns

Components & Cycles

Union-Find: lesson 4 of 4

Start the counter at n and drop it on every union that actually merges.

Lesson 4 of 4 · 5 min

Components & Cycles

Step 1 of 7

Six buildings, no cable laid. Every one is its own component, so the counter starts at 6.

The Idea

Give every element its own group and set a counter to n. Then walk the edges.

A union that merges two different roots drops the counter by one. A union that finds one shared root changes nothing — and that edge is exactly a cycle, because both ends were already reachable from each other. One pass answers both questions.

Real-World Example

A crew laying fibre between buildings. Each new cable either connects two networks that were separate — progress — or links two buildings already on the same loop, which is spare capacity, not coverage. The counter says how many crews are still needed.

The Code

parent = list(range(6))
def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x

edges = [(0, 1), (1, 2), (0, 2), (3, 4)]
components, cycles = 6, 0
for a, b in edges:
    ra, rb = find(a), find(b)
    if ra == rb: cycles += 1        # both ends already linked
    else: parent[ra], components = rb, components - 1
print(components, cycles)

Python

Your turn

What does this print?

parent = list(range(4))
def find(x):
  while parent[x] != x:
      x = parent[x]
  return x
count = 4
for a, b in [(0, 1), (2, 3), (1, 3)]:
  ra, rb = find(a), find(b)
  if ra != rb:
      parent[ra] = rb
      count -= 1
print(count)

Mini quiz

1 / 3

Starting from n singletons, the component count after processing edges is:

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.