iq.lab
Python starts when a code cell comes near or you run one
10 Graphs

Lesson 5 of 6

Union-find

Union-find keeps groups that only ever merge. Each item points at a parent, the root at the top names the group, and two small tricks keep the trees so flat that each lookup costs nearly O(1) over a run, so counting groups and catching the edge that closes a cycle both take one pass over the edges.

About 1 hour 40 minutes, with the 2 problems worked in it
By the end you can
  • Store groups as a parent list and find any item's root by walking up it

  • Merge two groups by pointing one root at the other, and keep a count of the groups left

  • Explain why union by size keeps every find within log₂ n steps, and what path compression adds

  • Use union-find to count connected components and to find the edge that closes a cycle

  • Say the walk, notebook, promise and cost of union-find out loud

Your customer table has duplicates. A matching job compares accounts and sends you pairs that belong to the same person: accounts 0 and 1 share an email, 1 and 2 share a phone number, 3 and 4 share a card. How many real customers are there? Accounts 0 and 2 share nothing directly, yet they are one person, because account 1 links them. So the answer is two: {0, 1, 2} and {3, 4}.

The pairs chain together, and that is what makes this hard. A chain can be any length. Worse, the job keeps running: every new pair may merge two customers you had counted as different.

In graph words: the accounts are nodes, each pair is an edge, and a customer is a connected component, the depth-first search lesson's name for a group of nodes that can all reach each other along edges, with no edge leaving the group. Union-find is a notebook built for groups that only ever merge. It answers "are these two in the same group?" and "merge these two groups" in a few steps each on average, in whatever order the pairs arrive.

A parent for every item

How should the notebook store the groups? The first idea is a label per item: group = [0, 0, 0, 3, 3] says items 0 to 2 are in group 0 and items 3 and 4 are in group 3. Checking "same group?" is one comparison, but merging is slow. To merge group 3 into group 0, every item labelled 3 must be relabelled, and finding them means scanning the whole list: O(n) per merge.

Union-find stores a parent instead of a label. Each item points at one item, its parent, in a list called parent. Follow the parents from any item and you always end at an item that is its own parent. That item is the root, and the root names the group. Two items are in the same group exactly when they reach the same root.

index012345
parent001244

Read it one item at a time. parent[0] is 0, so 0 is a root. Item 1 points at 0, item 2 at 1, and item 3 at 2, so all four reach 0. Item 4 is a root too, and item 5 points at it. Two roots, so two groups: {0, 1, 2, 3} and {4, 5}. Draw an arrow from each item to its parent and each group becomes a small tree: the root at the top, and every other item hanging below it by its arrow.

find(x) answers "which group is x in?" by walking up. Start at x, move to its parent, and stop at the first item that is its own parent. Before you step through, guess: how many steps up does the walk from item 3 take?

Step throughfind walks up to the root
Step 1 of 12
Line 1 is about to run.
parent = [0, 0, 1, 2, 4, 4]
x = 3
root = x
while parent[root] != root:
root = parent[root]
print(root)
Names
no names yet
Output
(nothing printed yet)

The same walk as a function:

def find(x):
    root = x
    while parent[root] != root:
        root = parent[root]
    return root
PredictClimb to the root

Follow each walk up the parent list and type exactly what the program prints.

parent = [1, 1, 1, 0, 3, 5]

def find(x):
    root = x
    while parent[root] != root:
        root = parent[root]
    return root

print(find(4), find(2), find(5))

A root is the only item that is its own parent, and every group has exactly one root. So counting groups means counting roots:

Work it outHow many groups?

How many groups does this parent list describe?

parent = [2, 1, 2, 1, 4, 2, 6]
groups

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Union: point one root at the other

Merging two groups takes one write. union(a, b) finds both roots. If they are the same, a and b are already in one group and nothing changes. Otherwise, point one root at the other: parent[root_b] = root_a. Every item that used to reach root_b now climbs one step further and reaches root_a, so the whole group moves with that one write.

The trace starts with four items, each its own root, and a count groups = 4. Each union that joins two different roots lowers the count by one. The first three pairs say that new accounts 1, 2 and 3 each match account 0, with the new account written first. Then the pair (2, 3) arrives. Before you step, guess what it does.

Step throughPlain union, edge by edge
Step 1 of 65
Line 1 is about to run.
[0, 1, 2, 3]: every item starts as a root, alone in its group.
parent = list(range(4))
groups = 4
def find(x):
root = x
while parent[root] != root:
root = parent[root]
return root
for a, b in [(1, 0), (2, 0), (3, 0), (2, 3)]:
root_a, root_b = find(a), find(b)
if root_a == root_b:
print("skip", a, b)
else:
parent[root_b] = root_a
groups -= 1
print(parent, groups)
Names
no names yet
Output
(nothing printed yet)

Comparing roots is what makes it correct. Before the pair (2, 3) arrived, items 2 and 3 had never been paired with each other, but they already shared root 3, so union-find knew they were connected.

The parent arrows are not the edges. The first three pairs joined 1, 2 and 3 each to 0, a star around 0. The parent list ends as a chain instead: 0 points at 1 and 1 points at 2, although no pair ever joined 1 and 2. Union-find keeps only who is in which group. Which item points at which depends on the order of the unions, and that is fine, because only roots are ever compared.

Work a few unions by hand. It is the fastest way to make the parent list feel like a picture.

On paperUnions by hand

Five items, 0 to 4, start as their own roots: parent = [0, 1, 2, 3, 4]. Apply these unions with the plain rule from the trace (find both roots; if they differ, parent[root_b] = root_a):

(0, 1), (2, 3), (1, 3), (4, 2)

Write the parent list after each union. Then count how many steps find(3) climbs at the end.

Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

steps find(3) climbs

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Keeping the trees short

A find costs one step per level it climbs, so tall trees make it slow. In the last trace, find(0) climbed 0, then 1, then 2 steps, because each union hung the whole chain under a new root. Keep the pattern going with n items and the pairs (1, 0), (2, 0), up to (n − 1, 0): the kth pair's find(0) climbs k − 1 steps. In total that is 0 + 1 + ... + (n − 2) = (n − 1)(n − 2) / 2 steps: 6 for 5 items, 498,501 for 1,000 items, and about 5 billion for 105. The plain version is O(n2) on a bad order of pairs. Two small changes fix it.

Union by size

Always hang the smaller group under the bigger one. A second list, size, holds for each root how many items its group has; every item starts at 1. When two roots meet, the root of the smaller group goes under the root of the bigger group, and the bigger root's size grows by the smaller's. On a tie either way works; the widget below and this module's problems all use one rule: the second root goes under the first.

root_a, root_b = find(a), find(b)
if root_a != root_b:
    if size[root_a] < size[root_b]:
        root_a, root_b = root_b, root_a   # now root_a's group is at least as big
    parent[root_b] = root_a
    size[root_a] += size[root_b]

Replay the bad pairs with this rule. (1, 0) is a tie between two single items, so 0 goes under 1 and size[1] becomes 2. For (2, 0), find(0) climbs one step to 1, whose group has 2 items, while 2's group has 1, so 2 goes under 1, not the other way round. (3, 0) does the same. The result is parent = [1, 1, 1, 1]: every other item sits one step below root 1.

Why does no tree get tall? An item moves one step further from its root only when its group is hung under another root, and union by size does that only when the other group is at least as big. So each time an item sinks a level, its group at least doubles. Start at 1 item and double: 2, 4, 8, and so on. Reaching n items takes log₂ n doublings (log₂ n is the number of times you can double 1 before you reach n: 3 for 8, about 20 for a million). So no item ever sits more than log₂ n steps below its root: at most 19 steps for a million items. Each find is O(log n).

Quick checkWhich root goes under?

A union finds root_a = 7, whose group has 2 items, and root_b = 2, whose group has 5 items. What does union by size do?

Choose one answer, then check.

Path compression

Path compression flattens the tree during the find itself. Once find knows the root, it walks the same path a second time and points every item on it straight at the root. The next find from any of those items takes one step. The trace runs it on the bad chain from before, grown to five items: plain union on the pairs (1, 0), (2, 0), (3, 0) and (4, 0) builds parent = [1, 2, 3, 4, 4]. Before you step through, guess the parent list after find(0).

Step throughfind with path compression
Step 1 of 27
Line 1 is about to run.
parent = [1, 2, 3, 4, 4]
x = 0
root = x
while parent[root] != root:
root = parent[root]
while parent[x] != root:
next_x = parent[x]
parent[x] = root
x = next_x
print(root, parent)
Names
no names yet
Output
(nothing printed yet)

Why next_x? Line 8 overwrites parent[x], so the old parent must be saved first: the walk still needs it to move up. It is the same move you make when reversing a linked list: save the next node before you re-point the current one.

Compression only changes the items on the path it walked. Predict what it leaves alone:

PredictWhat compression leaves alone

This find compresses the path it walks. Type exactly what the program prints.

parent = [1, 2, 3, 3, 2]

def find(x):
    root = x
    while parent[root] != root:
        root = parent[root]
    while parent[x] != root:
        next_x = parent[x]
        parent[x] = root
        x = next_x
    return root

print(find(0))
print(parent)

Now put find with compression together. It returns the root and leaves the path flat.

Put in orderfind with path compression

Put the lines in order to build find(parent, x), which returns the root of x and points every item on the path straight at that root. Here find takes the parent list as an argument, so it can be tested on its own. Indentation is part of each line. Two lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • return x
    • next_x = parent[x]
    • x = parent[x]
    • root = parent[root]
    • while parent[root] != root:
    • parent[x] = root
    • root = x
    • x = next_x
    • def find(parent, x):
    • return root
    • while parent[x] != root:

    You will also meet find written with recursion, in other people's solutions and on LeetCode:

    def find(x):
        if parent[x] != x:
            parent[x] = find(parent[x])   # point x at the root the inner call returns
        return parent[x]

    It does the same two walks. The calls climb to the root, and as each call returns, it points its item straight at the root. It is safe when union by size keeps the paths short: no path is longer than log₂ n, so at most 20 nested calls for a million items. On a long chain built by plain union, it goes one call deeper per item, and plain Python stops at about 1,000 nested calls by default (this lab allows 5,000). The loop version has no such limit.

    Both tricks at once

    The widget runs union by size and path compression together on six items, 0 to 5, and six unions. It shows the unions in order, the forest (every group's tree, side by side), and the parent list with each root's group size under it. The widget says "sets" where this lesson says groups. Before you press Next, guess: union 5 is (3, 5), so which root ends up on top?

    Here is the whole union-find in code, run on the widget's six unions. union returns True when it merges two groups, and False when the two items already share a root. Run it and compare the last line with the widget's last step.

    ⌘+Enter runs · edit freelyPython starts when a code cell comes near or you run one

    It prints True for the first five unions and False for (2, 4), then [0, 0, 0, 0, 0, 4] 1: the widget's parent list, and one group. That one True or False is all the next two sections need. Counting groups subtracts one per True, and the edge that closes a cycle is the first False.

    What does "nearly O(1)" mean? One find can still climb several steps, but it flattens everything it passes, so later finds are cheaper. The cost averaged over a long run of operations is the amortized cost, the same idea that makes list append amortized O(1) in module 2. With both tricks, the amortized cost of each operation is O(α(n)), where α(n) is the inverse Ackermann function. It grows so slowly that it is at most 4 for any n you could store. In the room, "nearly O(1) per operation, amortized" is the sentence to say.

    Recap: plain union can build a chain, and then a single find costs O(n). Union by size keeps every item within log₂ n steps of its root, and path compression flattens each path a find walks. Together they make union-find nearly O(1) per operation, amortized.

    Counting groups

    How many groups are there? Start the count at n, one group per item, and subtract one for each union that joins two different roots, because it turns two groups into one. A pair whose ends already share a root changes nothing. When the pairs run out, the count is the number of connected components.

    The matching job's next question: how many accounts does the biggest customer have? The size list already holds the answer, so keep a running maximum as the groups merge.

    Code itThe biggest customer

    Items are numbered 0 to n - 1, and each pair (a, b) says that a and b belong to the same group. Write largest_group(n, pairs), which returns how many items the biggest group has. Use union-find with union by size and path compression. Then press Watch it run to see size change.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    The first full problem gives the edges as a grid instead of a list: one row and one column per city, so each cell stands for a pair of cities, not a place on a map. Cities are numbered 0 to n − 1, and connected[i][j] is 1 when cities i and j share a road. Roads go both ways, so the grid is the same on both sides of the diagonal: read only the cells with j > i, and each road is seen once. Each road is a union, and the count starts at n.

    mediumUnion-findDepth-first search target 25 min

    Count the provinces

    A map shows n cities, numbered 0 to n - 1. You get an n by n grid connected of 0s and 1s: connected[i][j] is 1 when cities i and j have a direct road between them, and 0 when they do not. Roads go both ways, so connected[i][j] equals connected[j][i], and every city counts as linked to itself, so connected[i][i] is 1.

    Two cities are in the same province when you can drive from one to the other, on one road or a chain of roads. Every city belongs to exactly one province, and a city with no roads is a province by itself. Return the number of provinces.

    Example 1
    Inputconnected = [[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]Output2

    The roads 0 to 3 and 1 to 2 make two provinces: {0, 3} and {1, 2}.

    Example 2
    Inputconnected = [[1, 1, 0, 0], [1, 1, 1, 0], [0, 1, 1, 1], [0, 0, 1, 1]]Output1

    The roads are 0 to 1, 1 to 2 and 2 to 3. City 0 reaches city 3 through 1 and 2, so all four are one province.

    Example 3
    Inputconnected = [[1, 0, 1, 0, 0], [0, 1, 0, 0, 0], [1, 0, 1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 1]]Output3

    {0, 2}, {3, 4}, and city 1 on its own.

    Constraints
    • 1 ≤ n ≤ 1,000

    • connected[i][j] is 0 or 1

    • connected[i][i] is 1, and connected[i][j] equals connected[j][i]

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Reading the grid costs about n2 / 2 checks, and that dominates the unions, so the whole solution is O(n2). A depth-first search from each city that no earlier search reached also counts provinces in O(n2), and it is a fine answer to say first. The same count from a list of edges instead of a grid is LeetCode 323, in this module's practice set.

    The edge that closes a cycle

    union already tells you when an edge adds nothing: both finds return the same root. In a graph, such an edge closes a cycle: in the first lesson's words, a path that comes back to where it started without using any edge twice. (The problem below calls it a loop.) Its two ends were already connected, so the new edge makes a second route between them. In the widget, union 6, (2, 4), was exactly that.

    A tree, in graph terms (the graph's own edges, not union-find's parent arrows), is a set of n nodes joined by n − 1 edges so that every node reaches every other and there is no cycle. Add one extra edge to a tree and exactly one cycle appears. The next problem hands you that network with all n edges. Removing any edge on the cycle leaves a tree again, and the problem wants the one listed last. Walk the edges in order, uniting as you go. The first edge whose ends already share a root closes the cycle, and every other edge on the cycle came before it, so the first edge that union skips is the latest edge on the cycle.

    Try it by hand before the problem. Write down the groups after each edge.

    Quick checkWhich edge closes the cycle?

    Items 1 to 5 start as their own roots, and these edges arrive in order:

    [1, 2], [3, 4], [2, 3], [4, 1], [1, 5]

    Unite them one at a time. Which edge is the first one whose two ends already share a root?

    Choose one answer, then check.

    The problem labels its computers 1 to n, so parent gets n + 1 slots and slot 0 goes unused.

    mediumUnion-find target 25 min

    Redundant connection

    A network started out as a tree: n computers labeled 1 to n, joined by n - 1 two-way cables, so that every computer could reach every other one by exactly one route. Then someone added one more cable between two computers that were not joined directly. Now the network has a loop: a route that leaves a computer and comes back to it without using any cable twice.

    You get all n cables in edges, each as [a, b] with a < b. Remove one cable so that the network is a tree again: every computer still reaches every other one, and there is no loop. More than one cable always works. Return the one that appears latest in edges, as the list [a, b].

    Example 1
    Inputedges = [[1, 2], [2, 3], [3, 4], [2, 4]]Output[2, 4]

    The cables [2, 3], [3, 4] and [2, 4] make the loop 2, 3, 4. Removing any one of them leaves a tree, and [2, 4] is listed last.

    Example 2
    Inputedges = [[1, 2], [3, 4], [2, 3], [1, 4]]Output[1, 4]

    All four cables make one loop, 1, 2, 3, 4, so any of them works, and [1, 4] is listed last. Both ends of [2, 3] appeared earlier, but in separate groups, so [2, 3] does not close the loop.

    Example 3
    Inputedges = [[1, 3], [3, 4], [1, 4], [2, 4], [2, 5]]Output[1, 4]

    The loop is 1, 3, 4. Removing [2, 4] or [2, 5] would cut computers off, so they do not count even though they come later.

    Constraints
    • 3 ≤ n ≤ 105, and len(edges) == n

    • Every cable is [a, b] with 1 ≤ a < b ≤ n.

    • No cable is listed twice, and the cables connect all n computers.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Seen before is not the same as connected. The problem's example 2 has the exercise's trap: when [2, 3] arrives, both 2 and 3 have appeared already, but in different groups, {1, 2} and {3, 4}, so the edge merges them. Only the roots can tell connected apart from merely seen. Each edge costs two finds and at most one link, so the walk is nearly O(n).

    This module's practice bank has one more from the opening scene: Merge the accounts (LeetCode 721). The accounts share email addresses instead of arriving as numbered pairs, so a dict remembers the first account that listed each email, and the answer groups the emails by root.

    Last, practice that answer out loud. The words you write here are the words you will say in the room.

    Say itWhy union-find?

    The matching job now streams pairs of accounts, and after each pair a dashboard must show how many customers there are. Explain, as you would to an interviewer, how you would do it with union-find and why you would not run a depth-first search after each pair. Cover the walk, the notebook, the promise and the cost.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Weighted shortest paths