TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › Linked-List Sets and Weighted Union

Linked-List Sets and Weighted Union

The first real implementation of the disjoint-set operations (Disjoint-Set Operations and Connected Components) stores each set as a linked list. It makes FIND-SET a single pointer lookup, and its weakness, slow unions, is fixed by one rule of thumb with a clean proof: always move the smaller set. That rule, the weighted-union heuristic, brings mm operations down to O(m+nlg⁡n)O(m + n \lg n) time. The forests of the next lesson do even better, but the argument here, "an element can only be moved lg⁡n\lg n times because its set doubles every time", is one of the most reused ideas in algorithm analysis.

The representation

Each set is a linked list of its members, plus a small set object with pointers to the first member (the head, which is the representative), the last member (the tail) and the number of members. Each member stores its successor in the list and a pointer back to its set object.

text
set object S1: head ---> [ a ] ---> [ b ] ---> [ c ]      size 3
               tail ------------------------------^
               every member also points back to S1

MAKE-SET(x):    a new set object with one member x                       O(1)
FIND-SET(x):    return x.set.head                                         O(1)
UNION(x, y):    append y's list after x's tail; for each member v of y's
                list set v.set = x.set; discard y's set object            O(length of y's list)

FIND-SET follows two pointers. UNION has to rewrite the back pointer of every element it moves, and that is its cost.

The program builds exactly these objects, list nodes with next and set pointers and set objects with head, tail and size, and prints the lists after a few unions. It appends the second set to the first, as the description above says; the weighted version comes below.

python · try it yourself
class SetObject:
    __slots__ = ("head", "tail", "size")

class Member:
    __slots__ = ("name", "next", "set")

def make_set(name):
    x, s = Member(), SetObject()
    x.name, x.next, x.set = name, None, s
    s.head = s.tail = x
    s.size = 1
    return x

def find_set(x):
    return x.set.head                       # two pointer steps, O(1)

def union(x, y):
    a, b = x.set, y.set
    if a is b:
        return 0
    v, updated = b.head, 0
    while v is not None:                    # every member of b now points to a
        v.set = a
        updated += 1
        v = v.next
    a.tail.next = b.head                    # append b's list after a's tail
    a.tail = b.tail
    a.size += b.size
    return updated

def members(x):
    out, v = [], x.set.head
    while v is not None:
        out.append(v.name); v = v.next
    return out

e = {name: make_set(name) for name in "abcdef"}
for x, y in [("a", "b"), ("c", "d"), ("a", "c"), ("e", "a")]:
    k = union(e[x], e[y])
    print(f"union({x}, {y}): {k} back pointer(s) updated; set of {x}: {members(e[x])}, representative {find_set(e[x]).name}")
print("find_set(d):", find_set(e["d"]).name, "| find_set(f):", find_set(e["f"]).name)
union(a, b): 1 back pointer(s) updated; set of a: ['a', 'b'], representative a
union(c, d): 1 back pointer(s) updated; set of c: ['c', 'd'], representative c
union(a, c): 2 back pointer(s) updated; set of a: ['a', 'b', 'c', 'd'], representative a
union(e, a): 4 back pointer(s) updated; set of e: ['e', 'a', 'b', 'c', 'd'], representative e
find_set(d): e | find_set(f): f

The last union appended the four-element list onto the singleton e and had to update four back pointers. That is the weakness the rest of the lesson fixes.

A bad sequence

Without any rule about which list is appended to which, mm operations can take Θ(m2)\Theta(m^2) time. Take nn elements x1,…,xnx_1, \ldots, x_n, make them singleton sets, and then call UNION(x2,x1)(x_2, x_1), UNION(x3,x2)(x_3, x_2), …, UNION(xn,xn−1)(x_n, x_{n-1}), always appending the long list onto the new singleton. The ii-th union moves ii elements, so the n−1n - 1 unions update

∑i=1n−1i=n(n−1)2=Θ(n2)\sum_{i=1}^{n-1} i = \frac{n(n - 1)}{2} = \Theta(n^2)

back pointers, while the number of operations is only m=2n−1m = 2n - 1. The amortized cost per operation is Θ(n)\Theta(n).

Weighted union

Keep the size in each set object and, in UNION, always append the shorter list onto the longer one (ties either way). The bad sequence above now moves one element per union.

Theorem. With linked lists and the weighted-union heuristic, a sequence of mm MAKE-SET, UNION and FIND-SET operations, nn of them MAKE-SETs, takes O(m+nlg⁡n)O(m + n \lg n) time.

Proof. Everything except updating back pointers takes O(1)O(1) per operation, O(m)O(m) in total. Fix an element xx and look at the moments when its back pointer is updated. Each time, xx was in the smaller of the two sets, so the set that xx belongs to afterwards has at least twice as many elements as xx's set had before. The first update puts xx in a set of at least 2 elements, the second in one of at least 4, the kk-th in one of at least 2k2^k. No set has more than nn elements, so 2k≤n2^k \le n and xx's pointer is updated at most ⌊lg⁡n⌋\lfloor \lg n \rfloor times. Over all nn elements that is at most nlg⁡nn \lg n updates.

The program implements both versions and counts the back-pointer updates on the bad sequence and on random unions. It also records how many times the busiest element moved.

python · try it yourself
import math, random

class ListSets:
    def __init__(self, n, weighted):
        self.weighted = weighted
        self.set_of = list(range(n))                # member -> set id (the back pointer)
        self.members = [[x] for x in range(n)]      # set id -> its list; members[s][0] is the head
        self.updates, self.moved = 0, [0] * n
    def find(self, x):
        return self.members[self.set_of[x]][0]
    def union(self, x, y):
        a, b = self.set_of[x], self.set_of[y]
        if a == b:
            return
        if self.weighted and len(self.members[a]) < len(self.members[b]):
            a, b = b, a                             # move the smaller set b
        for v in self.members[b]:
            self.set_of[v] = a
            self.updates += 1
            self.moved[v] += 1
        self.members[a].extend(self.members[b])     # append b's list after a's tail
        self.members[b] = None

n = 1024
for weighted in [False, True]:
    ds = ListSets(n, weighted)
    for i in range(1, n):
        ds.union(i, i - 1)                          # always the old big set as the second argument
    print(f"bad sequence, {'weighted' if weighted else 'plain':8}: {ds.updates:7} pointer updates")

rng = random.Random(23)
ds = ListSets(n, True)
pairs = [(rng.randrange(n), rng.randrange(n)) for _ in range(5000)]
for x, y in pairs:
    ds.union(x, y)
assert all(ds.find(x) == ds.find(y) for x, y in pairs)
print(f"5000 random unions, weighted: {ds.updates} updates in total, "
      f"busiest element moved {max(ds.moved)} times (lg n = {int(math.log2(n))})")

ds = ListSets(n, True)                             # pair up sets of equal size, round by round
step = 1
while step < n:
    for i in range(0, n, 2 * step):
        ds.union(i, i + step)
    step *= 2
print(f"balanced rounds, weighted: {ds.updates} updates = (n/2) lg n, busiest element moved {max(ds.moved)} times")
bad sequence, plain   :  523776 pointer updates
bad sequence, weighted:    1023 pointer updates
5000 random unions, weighted: 1985 updates in total, busiest element moved 5 times (lg n = 10)
balanced rounds, weighted: 5120 updates = (n/2) lg n, busiest element moved 10 times

The plain version does 1+2+⋯+1023=523,7761 + 2 + \cdots + 1023 = 523{,}776 updates on the bad sequence, and the weighted version 1023. Random unions stay far below the bound: no element moved more than 5 times. The last experiment reaches it. Uniting sets of equal size in rounds (pairs, then fours, then eights) moves half of all elements in each of the lg⁡n\lg n rounds, and the element that is always in the moved half changes its pointer exactly lg⁡n=10\lg n = 10 times.

In C++

The C++ version stores the lists in arrays: next[v] links the members, and for each set id it keeps head, tail and size. UNION walks only the smaller list. The test makes 2000 elements, performs 100,000 random unions and finds with a fixed seed, checks the answers against a slow relabelling array, and reports the busiest element's move count.

cpp · try it yourself
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <random>
#include <utility>
#include <vector>

class ListSets {
    std::vector<int> set_, next_, head_, tail_, size_, moved_;
public:
    long updates = 0;
    explicit ListSets(int n) : set_(n), next_(n, -1), head_(n), tail_(n), size_(n, 1), moved_(n, 0) {
        for (int x = 0; x < n; ++x) set_[x] = head_[x] = tail_[x] = x;     // MAKE-SET for every x
    }
    int find(int x) const { return head_[set_[x]]; }
    void unite(int x, int y) {
        int a = set_[x], b = set_[y];
        if (a == b) return;
        if (size_[a] < size_[b]) std::swap(a, b);                           // b is the smaller set
        for (int v = head_[b]; v != -1; v = next_[v]) { set_[v] = a; ++updates; ++moved_[v]; }
        next_[tail_[a]] = head_[b];                                         // append b after a's tail
        tail_[a] = tail_[b];
        size_[a] += size_[b];
    }
    int busiest() const { return *std::max_element(moved_.begin(), moved_.end()); }
};

int main() {
    const int n = 2000;
    ListSets ds(n);
    std::vector<int> label(n);
    for (int x = 0; x < n; ++x) label[x] = x;
    std::mt19937 rng(23);
    int wrong = 0;
    for (int step = 0; step < 100000; ++step) {
        int x = static_cast<int>(rng() % n), y = static_cast<int>(rng() % n);
        if (rng() % 4 == 0) {                                                // a union
            ds.unite(x, y);
            int old = label[y], now = label[x];
            if (old != now) for (int& l : label) if (l == old) l = now;
        } else {                                                             // a query
            wrong += (ds.find(x) == ds.find(y)) != (label[x] == label[y]);
        }
    }
    std::printf("%d wrong answers; %ld pointer updates; busiest element moved %d times (lg n = %.1f)\n",
                wrong, ds.updates, ds.busiest(), std::log2(n));
}
0 wrong answers; 3767 pointer updates; busiest element moved 5 times (lg n = 11.0)

Where linked lists stop

With weighted union, FIND-SET is O(1)O(1) and the total cost of all unions is O(nlg⁡n)O(n \lg n). That is good, and the representation is still used where FIND-SET must be worst-case constant time. But the lg⁡n\lg n factor is real, as the balanced rounds showed: a union of two sets of equal size always moves half of their elements. The forest representation of the next lesson accepts slower finds in exchange for unions that change one pointer, and with two heuristics the total becomes O(m α(n))O(m \, \alpha(n)): Forests: Union by Rank and Path Compression.

Test yourself

With linked lists and weighted union, what does UNION of a 10-element set and a 3-element set cost?

  1. 1 pointer update
  2. 3 back-pointer updates, plus O(1)O(1)
  3. 10 back-pointer updates
  4. 13 updates

Why can an element's back pointer change at most ⌊lg⁡n⌋\lfloor \lg n \rfloor times under weighted union?

  1. Because each union halves the number of sets
  2. Because each time it moves, it was in the smaller set, so its set at least doubles, and no set exceeds nn elements
  3. Because FIND-SET is O(1)O(1)
  4. Because there are at most lg⁡n\lg n unions

Without weighted union, what is the worst-case total cost of n−1n - 1 unions on nn elements?

  1. Θ(n)\Theta(n)
  2. Θ(nlg⁡n)\Theta(n \lg n)
  3. Θ(n2)\Theta(n^2)
  4. Θ(n3)\Theta(n^3)