Skip to content

Union-find

storing

Level 3 of 3

Also called Disjoint-set forest and Merge-find set.

how it works

The idea, then one run, moment by moment.

Union-find answers one question fast: are two places in one group? Think of towns joined by new roads over time, asked again and again whether towns 3 and 7 are joined yet. It keeps places in groups, each with one leader. Every other place points at another in its group, and following the roads up always ends at the leader. Two places share a group when their finds end at one leader. To join two places, find each one's leader. If they differ, hang the smaller group's leader under the bigger's; for two groups the same size, the leader of the place named first under the other's. On the way up, straighten: point every place passed straight at the leader. Each road followed is one link, this page's count. The run below joins places 1 to 7 by 1-2, 3-4, 1-3, 1-5, 6-7 and 5-7; places 8 and 9 stay alone.

  1. step 11 of 32

    123456789

    1 points at 2, so follow the road up.

    roads followed: 1

  2. step 13 of 32

    123456789

    3 points at 4, so follow the road up.

    roads followed: 2

  3. step 15 of 32

    123456789

    Both groups have 2 places, so hang 2 under 4.

    roads followed: 2

Join 3 is 1-3. Place 1 follows one road to 2, and 3 one road to 4: 2 links. Each picture counts this join's roads only. Two groups the same size, and 1 is named first, so 1's leader, 2, goes under 4.
  1. step 17 of 32

    123456789

    1 points at 2, so follow the road up.

    roads followed: 1

  2. step 18 of 32

    123456789

    2 points at 4, so follow the road up.

    roads followed: 2

  3. step 20 of 32

    123456789

    Point every place passed straight at 4, so the next find is shorter.

    roads followed: 2

  4. step 22 of 32

    123456789

    5's group has one place and 4's has 4 places, so hang the smaller group's leader, 5, under 4.

    roads followed: 2

Join 4 is 1-5. Place 1 follows two roads up to 4, then points straight at 4. 5's group holds 1 place and 4's holds 4, so 5 hangs under 4: 2 links.
Joining, and a path made straight: 8 moments of its 32 steps, the steps between them left for the watch page
  1. step 1 of 32

    123456789

    Every place is a group of its own, and 6 joins to make.

    what it remembers to know where it is
    doing join
    not yet
    looking at
    not yet
    groups
    9

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 5 of 32

    123456789

    Both groups have one place, so hang 1 under 2.

    what it remembers to know where it is
    doing join
    1
    looking at
    not yet
    groups
    8

    Where it says not yet, nothing is held there at that moment.

    watch from here

  3. step 9 of 32

    123456789

    Both groups have one place, so hang 3 under 4.

    what it remembers to know where it is
    doing join
    2
    looking at
    not yet
    groups
    7

    Where it says not yet, nothing is held there at that moment.

    watch from here

  4. step 26 of 32

    123456789

    Both groups have one place, so hang 6 under 7.

    what it remembers to know where it is
    doing join
    5
    looking at
    not yet
    groups
    4

    Where it says not yet, nothing is held there at that moment.

    watch from here

  5. step 28 of 32

    123456789

    5 points at 4, so follow the road up.

    what it remembers to know where it is
    doing join
    6
    looking at
    5
    groups
    4

    watch from here

  6. step 30 of 32

    123456789

    7 points at nothing, so it leads the group 7 is in.

    what it remembers to know where it is
    doing join
    6
    looking at
    7
    groups
    4

    watch from here

  7. step 31 of 32

    123456789

    7's group has 2 places and 4's has 5 places, so hang the smaller group's leader, 7, under 4.

    what it remembers to know where it is
    doing join
    6
    looking at
    not yet
    groups
    3

    Where it says not yet, nothing is held there at that moment.

    watch from here

  8. step 32 of 32

    123456789

    Done. The places are in 3 groups.

    what it remembers to know where it is
    doing join
    not yet
    looking at
    not yet
    groups
    3

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. every place starts as a group of its own, pointing at nothingPython lines 7 and 8
  2. to join two places, find each one's leaderPython lines 19 and 20
  3. follow the roads up until a place points at nothing: that is the leaderPython lines 10, 11, 12, 13 and 14
  4. then point every place passed straight at the leaderPython lines 15, 16 and 17
  5. if the leaders differ, hang the smaller group's leader under the other'sPython lines 23, 24, 25 and 26
  6. two groups of one size: either onePython line 25
  7. if they are the same, the two places are already joinedPython lines 21 and 22
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def union_find(joins, n=9):
    """Join places 1 to n into groups, one join at a time.

    Each place points at another in its group, or at itself when it leads
    the group. Returns where each place points, place 1 first.
    """
    parent = list(range(n + 1))  # every place leads a group of its own
    size = [1] * (n + 1)

    def find(p):
        passed = []
        while parent[p] != p:  # follow the roads up until a place points at itself, as a leader does
            passed.append(p)
            p = parent[p]
        for q in passed:  # then point every place passed straight at the leader
            parent[q] = p
        return p

    for a, b in joins:  # to join two places, find each one's leader
        ra, rb = find(a), find(b)
        if ra == rb:  # the same leader: already joined
            continue
        if size[ra] > size[rb]:  # hang the smaller group's leader under the other's
            ra, rb = rb, ra
        parent[ra] = rb  # two groups of one size: a's leader goes under b's
        size[rb] += size[ra]
    return parent[1:]

how it scales

Links counted for 10 to 100,000 places. Places start as groups of one, and each join makes two groups one, so they need one join fewer than the places: 9 places, 8 joins. The plot draws joins picked at random.

Each mark across or up is ten times the one before, a log-log plot. Picked at random, the joins follow about 99 links at 100 places and about 1,090 at 1,000. That is one mark up for each mark across, so the links grow in step with the places. Each point is the mean of 20 orders. Pair by pair, counted exactly in section 4, follows 146 and 1,496.

roads followed, ten times more at each mark up

102104106101102103104105106107101102103104105106101102103104105106107101102103104105106101102103104105106107

nn, how many places there are, ten times more at each mark to the right

  • joins picked at randompoints only, each measured by a real run, since no single formula for the roads followed of this row is worked out here
what joins picked at random cost on average, at a billion links a second
nnroads followedtime
1,0001,090about 1.1 microseconds
100,000111,863about 112 microseconds

The roads followed are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count union-find's links yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it joins places 1 to n
into one group by n - 1 joins, and prints the links followed for the
pair-by-pair order and the average over 20 orders picked at random. A link is
one road followed while finding a leader. The counts are the same on any
computer; only the time differs.
"""
import random


def union_find(joins, n=9):
    """Join places 1 to n into groups, one join at a time.

    Each place points at another in its group, or at itself when it leads
    the group. Returns where each place points, place 1 first.
    """
    parent = list(range(n + 1))  # every place leads a group of its own
    size = [1] * (n + 1)

    def find(p):
        passed = []
        while parent[p] != p:  # follow the roads up until a place points at itself, as a leader does
            passed.append(p)
            p = parent[p]
        for q in passed:  # then point every place passed straight at the leader
            parent[q] = p
        return p

    for a, b in joins:  # to join two places, find each one's leader
        ra, rb = find(a), find(b)
        if ra == rb:  # the same leader: already joined
            continue
        if size[ra] > size[rb]:  # hang the smaller group's leader under the other's
            ra, rb = rb, ra
        parent[ra] = rb  # two groups of one size: a's leader goes under b's
        size[rb] += size[ra]
    return parent[1:]


def pair_by_pair(n):
    """1-2, 3-4 and 1-3, then each new pair joined, and joined to the place left two roads deep."""
    if n < 4:
        return [(1, 2), (1, 3)][: n - 1]
    joins = [(1, 2), (3, 4), (1, 3)]
    deep, p = 1, 5
    while p + 1 <= n:
        joins += [(p, p + 1), (deep, p)]
        deep, p = p, p + 2
    if p <= n:
        joins.append((deep, p))
    return joins


def picked(n):
    """n - 1 joins, each of two places picked at random from different groups."""
    group = list(range(n + 1))

    def top(p):
        while group[p] != p:
            group[p] = group[group[p]]  # skip a step on the way: same leader, shorter roads next time
            p = group[p]
        return p

    joins = []
    while len(joins) < n - 1:
        a, b = random.randint(1, n), random.randint(1, n)
        if top(a) != top(b):
            group[top(a)] = top(b)
            joins.append((a, b))
    return joins


def count(joins):
    """Join as union_find() does, counting each road followed: the links the plot counts."""
    n = max([9] + [p for join in joins for p in join])
    parent = list(range(n + 1))
    size = [1] * (n + 1)
    links = 0

    def find(p):
        nonlocal links
        passed = []
        while parent[p] != p:
            links += 1
            passed.append(p)
            p = parent[p]
        for q in passed:
            parent[q] = p
        return p

    for a, b in joins:
        ra, rb = find(a), find(b)
        if ra == rb:
            continue
        if size[ra] > size[rb]:
            ra, rb = rb, ra
        parent[ra] = rb
        size[rb] += size[ra]
    return links


if __name__ == "__main__":
    random.seed(1)
    print(f"{'n':>7} {'pair by pair':>13} {'picked at random':>18}")
    for n in [10, 100, 1000, 10000]:
        average = sum(count(picked(n)) for _ in range(20)) / 20
        print(f"{n:>7} {count(pair_by_pair(n)):>13} {average:>18.1f}")

best, worst and average

Joins that name two leaders every time follow no road: 0 links. That case is not plotted, as a log-log plot's marks go 1, 10, 100, each ten times the last, and never reach 0. The dearest order is known only for small sizes. Every order was tried for 2 to 9 places, and pair by pair always follows the most; at 9 places it is 1-2, 3-4, 1-3, 5-6, 1-5, 7-8, 5-7, 7-9. At 10 places it no longer does: 1-2, 3-4, 1-3, 5-6, 7-8, 5-7, 1-5, 1-9, 2-10 follows 12 links to its 11. So there is no worst column. Section 4 bounds the dearest order: at least pair by pair's ⌊3n−72⌋\lfloor \frac{3n - 7}{2} \rfloor, at most 2(n−1) log⁡2 n2(n - 1)\,\log_2\, n. The books cite a lower ceiling still, proved in research and beyond this page (volume three, chapter 33).

A case is one kind of input, the thing the method is given, such as joins picked at random, however many places. A bound says how fast that case's cost grows as more places join.

The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
averagejoins picked at random
roads followedmeasured, at most 2(n−1) log⁡2 n2(n - 1)\,\log_2\, n: about 99 at 100
how the roads followed grow in each case
tight, Θ\Thetanot worked out here
ceiling, OOO(n log⁡2 n)O(n \,\log_2\, n), as every order
floor, Ω\Omeganot worked out here

extra memory: two numbers a place, where it points and its group's size

Extra memory is the room it needs on top of the input itself, while it runs.

  1. step 27 of 30

    123456789

    4 points at nothing, so it leads the group 4 is in.

    roads followed: 0

  2. step 28 of 30

    123456789

    8 points at nothing, so it leads the group 8 is in.

    roads followed: 0

  3. step 29 of 30

    123456789

    Both groups have 4 places, so hang 4 under 8.

    roads followed: 0

Leaders only: 1-2, 3-4, 5-6, 7-8, 2-4, 6-8, 4-8. Both places of every join already lead their groups, so no join follows a road, 0 links. Here places 4 and 8 each lead a group of 4.
placesthe most links any order followspair by pairpairs, then pairs of pairs
5444
6555
7776
8888
9101010
Every order of joins tried, rows for 5 to 9 places. Pair by pair always reaches the most. Pairs, then pairs of pairs, the first guess at a dear order, at 7 places 1-2, 3-4, 5-6, 1-3, 5-7, 1-5, falls one short.
  1. step 39 of 46

    123456789

    1 points at 4, so follow the road up.

    roads followed: 1

  2. step 41 of 46

    123456789

    5 points at 6, so follow the road up.

    roads followed: 2

  3. step 42 of 46

    123456789

    6 points at 8, so follow the road up.

    roads followed: 3

  4. step 44 of 46

    123456789

    Point every place passed straight at 8, so the next find is shorter.

    roads followed: 3

  5. step 45 of 46

    123456789

    Both groups have 4 places, so hang 4 under 8.

    roads followed: 3

The joins 1-2, 3-4, 1-3, 1-3, 5-6, 7-8, 5-7, 1-5. The second 1-3 joins nothing but straightens 1 to point at 4. The last, 1-5, meets two groups of 4, so place 4 goes under 8, and 1 sinks: two roads below 8 again.

where the formula comes from

Each count above, worked out line by line. Each reason names the line it uses.

Why does pair by pair cost ⌊3n−72⌋\lfloor \frac{3n - 7}{2} \rfloor links?
  1. the move: the first four places

    the line:
    1-2, 3-4 and 1-3cost 2 links\begin{gathered} \text{1-2, 3-4 and 1-3} \\ \text{cost 2 links} \end{gathered}
    1. step 11 of 28

      123456789

      1 points at 2, so follow the road up.

      roads followed: 1

    2. step 13 of 28

      123456789

      3 points at 4, so follow the road up.

      roads followed: 2

    3. step 15 of 28

      123456789

      Both groups have 2 places, so hang 2 under 4.

      roads followed: 2

    Place 1 is now two roads below 4, the deep place.

    why it is allowed: 1-2 and 3-4 join leaders, 0 links. 1-3 follows one road from each, 2 links. Place 2 hangs under 4, so place 1 is now two roads deep.

  2. the move: each new pair

    the line:
    each new paircosts 3 links\begin{gathered} \text{each new pair} \\ \text{costs 3 links} \end{gathered}
    1. step 21 of 28

      123456789

      1 points at 2, so follow the road up.

      roads followed: 1

    2. step 22 of 28

      123456789

      2 points at 4, so follow the road up.

      roads followed: 2

    3. step 24 of 28

      123456789

      Point every place passed straight at 4, so the next find is shorter.

      roads followed: 2

    4. step 25 of 28

      123456789

      5 points at 6, so follow the road up.

      roads followed: 3

    5. step 27 of 28

      123456789

      6's group has 2 places and 4's has 4 places, so hang the smaller group's leader, 6, under 4.

      roads followed: 3

    1-5 follows 3 roads in all, and leaves place 5 two roads below 4.
    after the first fourjoinslinksthe deep place after
    the pair 5 and 65-6, then 1-535
    the pair 7 and 87-8, then 5-737
    9 alone7-92none
    Pair by pair at 9 places, after 1-2, 3-4 and 1-3. Each pair hands the deep place on.

    why it is allowed: Joining the pair, 5-6, follows nothing. Then 1-5: 1 follows two roads, to 2 and 4, and 5 one, to 6. 4's group always holds 4 places or more, more than the pair's 2, so 6 hangs under 4 every time, and 5 is the new deep place. The table follows each pair to 9 places.

  3. the move: a last place alone

    the line:
    a last place alonecosts 2 links\begin{gathered} \text{a last place alone} \\ \text{costs 2 links} \end{gathered}
    1. step 41 of 47

      123456789

      7 points at 8, so follow the road up.

      roads followed: 1

    2. step 42 of 47

      123456789

      8 points at 4, so follow the road up.

      roads followed: 2

    3. step 46 of 47

      123456789

      9's group has one place and 4's has 8 places, so hang the smaller group's leader, 9, under 4.

      roads followed: 2

    At 9 places the last join is 7-9. Place 7 follows 2 roads, to 8 and then 4, and 9 leads itself, 2 links.

    why it is allowed: When one place is left over, join the deep place to it. The deep place follows 2 roads, and the place alone leads itself.

  4. the move: add them up

    the line:
    W=2+3⌊n−42⌋+2 if n is odd\begin{gathered} W = 2 + 3 \lfloor \frac{n - 4}{2} \rfloor \\ + \text{2 if } n \text{ is odd} \end{gathered}

    why it is allowed: WW is the links pair by pair follows. By lines 1 to 3: after the first four, the other n−4n - 4 places make ⌊n−42⌋\lfloor \frac{n - 4}{2} \rfloor pairs, and one is left alone when nn is odd. At 6 places, one pair: 2 + 3 = 5.

  5. the move: even n, over 2

    the line:
    2+3⋅n−42=4+3n−1222 + 3 \cdot \frac{n - 4}{2} = \frac{4 + 3n - 12}{2}

    why it is allowed: For even nn, the n−4n - 4 places make n−42\frac{n - 4}{2} pairs and none is alone, so line 4 reads as the left side: at 6, 2 + 3 × 1 = 5. 2 is 4 halves, and 3 times n−4n - 4 is 3n−123n - 12. At 6, both sides are 5.

  6. the move: even n, the top

    the line:
    4+3n−122=3n−82\frac{4 + 3n - 12}{2} = \frac{3n - 8}{2}

    why it is allowed: The top, 4+3n−124 + 3n - 12, is 3n−83n - 8. At 6, 10 halves, 5.

  7. the move: odd n, over 2

    the line:
    2+3⋅n−52+2=8+3n−1522 + 3 \cdot \frac{n - 5}{2} + 2 = \frac{8 + 3n - 15}{2}

    why it is allowed: For odd nn, one of the n−4n - 4 places is alone, so the other n−5n - 5 make n−52\frac{n - 5}{2} pairs, and line 4 reads as the left side. The two 2s are 8 halves, and 3 times n−5n - 5 is 3n−153n - 15. At 7, 3 places: 1 pair and 1 alone, both sides 7.

  8. the move: odd n, the top

    the line:
    8+3n−152=3n−72\frac{8 + 3n - 15}{2} = \frac{3n - 7}{2}

    why it is allowed: The top, 8+3n−158 + 3n - 15, is 3n−73n - 7. At 7, 14 halves, 7.

  9. the move: one formula

    the line:
    W=⌊3n−72⌋W = \lfloor \frac{3n - 7}{2} \rfloor
    placesline 43n−82\frac{3n - 8}{2}3n−72\frac{3n - 7}{2}line 9
    4222.52
    543.544
    6555.55
    776.577
    8888.58
    9109.51010
    Rounding the fourth column down always gives line 4.

    why it is allowed: For even nn, 3n−72\frac{3n - 7}{2} is line 6's whole count plus a half, so it rounds down to line 6. For odd nn, line 8's 3n−72\frac{3n - 7}{2} is a count, whole already. The table shows 4 to 9 places.

  10. the move: drop the rounding and the 7

    the line:
    W≤3n2W \le \frac{3n}{2}

    why it is allowed: Line 9 rounds 3n−72\frac{3n - 7}{2} down, which is less than 3n2\frac{3n}{2}. At 6, 5 is at most 9.

  11. the move: read it as a bound

    the line:
    W∈O(n)W \in O(n)

    why it is allowed: By line 10, with the fixed multiple 1.5.

  12. the move: a floor

    the line:
    W≥3n−82W \ge \frac{3n - 8}{2}

    why it is allowed: By lines 6 and 8, even nn gives exactly 3n−82\frac{3n - 8}{2}, and odd nn gives 3n−72\frac{3n - 7}{2}, a half more.

  13. the move: take the tops away

    the line:
    3n−82−n−42=2n−42\frac{3n - 8}{2} - \frac{n - 4}{2} = \frac{2n - 4}{2}

    why it is allowed: 3n−83n - 8 less n−4n - 4 is 2n−42n - 4. At 6, 5 less 1 is 4.

  14. the move: a simpler floor

    the line:
    W≥n−2W \ge n - 2

    why it is allowed: Line 12 less n−42\frac{n - 4}{2}, which is not below 0 for 4 or more places, and taking away a number not below 0 keeps a floor. By line 13 what is left is 2n−42\frac{2n - 4}{2}, which is n−2n - 2. At 6, 5 is at least 4.

  15. the move: read it as a bound

    the line:
    W∈Ω(n)W \in \Omega(n)

    why it is allowed: By line 14. n−2n - 2 is at least half of nn for 4 or more places.

  16. the move: ceiling and floor together

    the line:
    W∈Θ(n)W \in \Theta(n)

    why it is allowed: Lines 11 and 15 bound WW by the same growth, nn.

try it with a small nn: at n=6n = 6, line 4 gives W=5W = 5, which you can work out by hand

Why do no n−1n - 1 joins into one group follow more than 2(n−1) log⁡2 n2(n - 1)\,\log_2\, n links?
  1. the move: when a place sinks

    the line:
    a place sinks only whenits group is hung underone as big or bigger\begin{gathered} \text{a place sinks only when} \\ \text{its group is hung under} \\ \text{one as big or bigger} \end{gathered}
    1. step 28 of 32

      123456789

      5 points at 4, so follow the road up.

      roads followed: 1

    2. step 31 of 32

      123456789

      7's group has 2 places and 4's has 5 places, so hang the smaller group's leader, 7, under 4.

      roads followed: 1

    The group of 6 and 7 holds 2, the group of 4 holds 5. So 7 hangs under 4, and 6 sinks one road, to two roads below 4.

    why it is allowed: It sinks one road only when its leader is hung, and the one hung is the smaller group's leader, or in a tie, the leader of the place named first.

  2. the move: roads at most sinkings

    the line:
    its roads below the leaderare at most its sinkings\begin{gathered} \text{its roads below the leader} \\ \text{are at most its sinkings} \end{gathered}

    why it is allowed: A place starts 0 roads below its leader, each sinking adds one, and straightening only brings places closer. Place 6 sank twice, under 7 and then with 7 under 4, and sits 2 roads below 4.

  3. the move: each sinking doubles

    the line:
    after sinking d times, itsgroup holds at least 2d\begin{gathered} \text{after sinking } d \text{ times, its} \\ \text{group holds at least } 2^d \end{gathered}
    times sunkits group holds at least
    01
    12
    24
    38
    416
    With 9 places, no place sinks a fourth time, as that needs 16.

    why it is allowed: By line 1, each time it sinks, its group joins one at least as big, so it at least doubles. 6's group of 2 joined one of 5, and now holds 7.

  4. the move: a group holds at most n

    the line:
    2d is at most n\begin{gathered} 2^d \text{ is at most } n \end{gathered}

    why it is allowed: By line 3, a place sunk dd times has at least 2d2^d places in its group, and no group holds more than all nn.

  5. the move: so d is small

    the line:
    d is at most  log⁡2 n\begin{gathered} d \text{ is at most } \,\log_2\, n \end{gathered}

    why it is allowed: By line 4, 1 doubled dd times is at most nn, and log⁡2 n\log_2\, n is how many times 1 doubles to reach nn, by the page on halving and logarithms. With 9 places, 1 doubled 3 times is 8, at most 9, and 4 times is 16, too many; dd counts sinkings, a whole number, so at most 3.

  6. the move: a find is short

    the line:
    a find follows at mostlog⁡2 n roads\begin{gathered} \text{a find follows at most} \\ \log_2\, n \text{ roads} \end{gathered}

    why it is allowed: By line 2, a place sits at most dd roads below its leader, and by line 5, dd is at most log⁡2 n\log_2\, n.

  7. the move: price a join

    the line:
    a join follows at most2 log⁡2 n links\begin{gathered} \text{a join follows at most} \\ 2\,\log_2\, n \text{ links} \end{gathered}

    why it is allowed: By line 6. Its two finds each follow at most log⁡2 n\log_2\, n roads.

  8. the move: add the joins

    the line:
    U=2(n−1) log⁡2 nU = 2(n - 1)\,\log_2\, n
    placesthe most links any order followsceiling UU
    5418.58
    6525.85
    7733.69
    8842.00
    91050.72
    Every order tried, against the ceiling.

    why it is allowed: UU is n−1n - 1 joins times line 7's most, so no order follows more. At 6 places, 2 times 5 joins is 10. The log⁡2\log_2 of 6 is between 2 and 3, as 6 lies between 4 and 8: about 2.585 by a calculator, so about 25.85.

  9. the move: a simpler ceiling

    the line:
    U≤2n log⁡2 nU \le 2n\,\log_2\, n

    why it is allowed: By line 8, as n−1n - 1 is less than nn.

  10. the move: read it as a bound

    the line:
    U∈O(n log⁡2 n)U \in O(n \,\log_2\, n)

    why it is allowed: By line 9, with the fixed multiple 2.

  11. the move: read it

    the line:
    the dearest order and theaverage are O(n log⁡2 n)\begin{gathered} \text{the dearest order and the} \\ \text{average are } O(n \,\log_2\, n) \end{gathered}

    why it is allowed: By lines 8 and 10: every order follows at most UU, so the dearest does, and so does their average. The dearest follows at least pair by pair's WW, by the first question, so it is Ω(n)\Omega(n) as well.

try it with a small nn: at n=6n = 6, line 8 gives UU, about 25.85

count it yourself

Count every link as places 1 to 6 are joined pair by pair, 1-2, 3-4, 1-3, 5-6 and 1-5. Each place's road is written as where it points: 1 → 2 means place 1 points at place 2. Places 7, 8 and 9 stay alone.

1-2, 3-4, 1-3, 5-6, 1-5, every step written down
stepwhere each place pointswhat happensroads followed
1Every place is a group of its own, and 5 joins to make.0
2To join 1 and 2, find each one's leader.0
31 points at nothing, so it leads the group 1 is in.0
42 points at nothing, so it leads the group 2 is in.0
51 → 2Both groups have one place, so hang 1 under 2.1 → 20
61 → 2To join 3 and 4, find each one's leader.1 → 20
71 → 23 points at nothing, so it leads the group 3 is in.1 → 20
81 → 24 points at nothing, so it leads the group 4 is in.1 → 20
91 → 2, 3 → 4Both groups have one place, so hang 3 under 4.1 → 2, 3 → 40
101 → 2, 3 → 4To join 1 and 3, find each one's leader.1 → 2, 3 → 40
111 → 2, 3 → 41 points at 2, so follow the road up.1 → 2, 3 → 41
121 → 2, 3 → 42 points at nothing, so it leads the group 1 is in.1 → 2, 3 → 41
131 → 2, 3 → 43 points at 4, so follow the road up.1 → 2, 3 → 42
141 → 2, 3 → 44 points at nothing, so it leads the group 3 is in.1 → 2, 3 → 42
151 → 2, 2 → 4, 3 → 4Both groups have 2 places, so hang 2 under 4.1 → 2, 2 → 4, 3 → 42
161 → 2, 2 → 4, 3 → 4To join 5 and 6, find each one's leader.1 → 2, 2 → 4, 3 → 42
171 → 2, 2 → 4, 3 → 45 points at nothing, so it leads the group 5 is in.1 → 2, 2 → 4, 3 → 42
181 → 2, 2 → 4, 3 → 46 points at nothing, so it leads the group 6 is in.1 → 2, 2 → 4, 3 → 42
191 → 2, 2 → 4, 3 → 4, 5 → 6Both groups have one place, so hang 5 under 6.1 → 2, 2 → 4, 3 → 4, 5 → 62
201 → 2, 2 → 4, 3 → 4, 5 → 6To join 1 and 5, find each one's leader.1 → 2, 2 → 4, 3 → 4, 5 → 62
211 → 2, 2 → 4, 3 → 4, 5 → 61 points at 2, so follow the road up.1 → 2, 2 → 4, 3 → 4, 5 → 63
221 → 2, 2 → 4, 3 → 4, 5 → 62 points at 4, so follow the road up.1 → 2, 2 → 4, 3 → 4, 5 → 64
231 → 2, 2 → 4, 3 → 4, 5 → 64 points at nothing, so it leads the group 1 is in.1 → 2, 2 → 4, 3 → 4, 5 → 64
241 → 4, 2 → 4, 3 → 4, 5 → 6Point every place passed straight at 4, so the next find is shorter.1 → 4, 2 → 4, 3 → 4, 5 → 64
251 → 4, 2 → 4, 3 → 4, 5 → 65 points at 6, so follow the road up.1 → 4, 2 → 4, 3 → 4, 5 → 65
261 → 4, 2 → 4, 3 → 4, 5 → 66 points at nothing, so it leads the group 5 is in.1 → 4, 2 → 4, 3 → 4, 5 → 65
271 → 4, 2 → 4, 3 → 4, 5 → 6, 6 → 46's group has 2 places and 4's has 4 places, so hang the smaller group's leader, 6, under 4.1 → 4, 2 → 4, 3 → 4, 5 → 6, 6 → 45
281 → 4, 2 → 4, 3 → 4, 5 → 6, 6 → 4Done. The places are in 4 groups.1 → 4, 2 → 4, 3 → 4, 5 → 6, 6 → 45

In all, 5 roads followed. The formula from section 4, ⌊3n−72⌋\lfloor \frac{3n - 7}{2} \rfloor, gives W=5W = 5 at n=6n = 6: the same.

where you meet it

Two widely used Python libraries keep groups with union-find.

  • networkx's cheapest lines

    networkx, a library for measuring networks of things, finds the cheapest lines that join every town by Kruskal's method. It tries lines cheapest first, and keeps one only if its two towns are in different groups, their leaders different. Its union-find hangs by size and straightens.

    source: the networkx source, networkx/utils/union_find.py (opens in a new tab), used in networkx/algorithms/tree/mst.py (opens in a new tab)

  • scikit-image's blobs

    scikit-image, a library for pictures, numbers every blob in a picture whose pixels hold numbers. Touching pixels of one number are joined, side by side or, unless told otherwise, at a corner. Every pixel's leader names its blob, numbered from 1, and the background is 0.

    source: the scikit-image source, src/skimage/measure/_ccomp.pyx (opens in a new tab) at version 0.26.0, behind its label function for pictures of numbers

linepriceits two townskept
1-21different groupsyes, 1 and 2 joined
3-42different groupsyes, 3 and 4 joined
1-33different groupsyes, all four joined
2-44one groupno
Kruskal's method on 4 towns. Each town is a place, and keeping a line is a join. The cheapest three lines join every town; 2-4 joins two towns already joined, a loop.
rowabcd
11102
21002
30022
Twelve pixels after labelling. The dark ones hold their blob's number, the background 0. Each blob's pixels are one group, its leader naming it.

what is used instead

To ask once whether two towns are joined, walk the lines between them. Union-find is worth it when joins and questions, such as whether towns 3 and 7 share a group, come mixed, many of each.

how it compares

Two ways to keep places in groups, set side by side by what each step costs.

waydo two places share a groupjoin two groupsmemory
union-findfind both leaders, at most log⁡2 n\log_2\, n roads eachfind both leaders, then hang onetwo numbers a place
a group name on every placecompare the two names, no roadrename every place of the smaller group, up to half the placesone name a place
Both answer whether two places share a group. With 1,000 places, joining two groups of 500 renames 500 places, where a union-find find follows at most about 10 roads, as 1 doubled 10 times is 1,024.
place12345
namesAABBB
after joining 1 and 3BBBBB
A name on every place. Joining 1's group to 3's renames the smaller group, A, places 1 and 2.