Disjoint sets
Tracking connections: the disjoint sets interface, quick find, quick union and its tall trees, weighted quick union with a logarithmic height bound, path compression, and where union–find is used.
- CS61B
- Disjoint Sets · Textbook Ch. 14
- Swift book
- Structures and Classes
Some questions are only about connection. Are these two computers on the same network? Can water flow from the top of this rock to the bottom? Are these two pixels part of the same region of an image? The data structure for them, disjoint sets (also called union–find), supports just two operations, and CS61B uses it to show how much the choice of representation matters: four designs, from hopeless to nearly perfect.
The interface
There are N items, numbered 0 to N − 1. At first each is alone. Then:
connect(p, q)joins the groups containingpandq.isConnected(p, q)asks whetherpandqare in the same group.
Connection is an equivalence: every item is connected to itself; if p is
connected to q, then q is connected to p; and connections chain, so if
p–q and q–r are connected, so are p and r. The groups are therefore
disjoint sets, and connect merges two of them.
protocol DisjointSets {
init(count: Int)
mutating func connect(_ p: Int, _ q: Int)
func isConnected(_ p: Int, _ q: Int) -> Bool
}
Nothing in the interface asks for the actual paths between items, only whether one exists. That restriction is what makes a fast implementation possible.
Quick find
The simplest representation stores, for each item, the id of its set:
item: 0 1 2 3 4 5
id: 0 0 2 2 2 5 sets {0, 1}, {2, 3, 4}, {5}
isConnected(p, q) compares two ids, which takes constant time. But
connect(p, q) must relabel every item in p’s set with q’s id, and finding
them means scanning all N items:
struct QuickFind {
private var id: [Int]
init(count: Int) {
id = Array(0..<count)
}
mutating func connect(_ p: Int, _ q: Int) {
let (old, new) = (id[p], id[q])
for i in id.indices where id[i] == old {
id[i] = new
}
}
func isConnected(_ p: Int, _ q: Int) -> Bool {
id[p] == id[q]
}
}
var sets = QuickFind(count: 6)
sets.connect(0, 1)
sets.connect(2, 3)
sets.connect(3, 4)
print(sets.isConnected(0, 1), sets.isConnected(1, 2), sets.isConnected(2, 4)) // true false true
connect is Θ(N), so connecting N items takes Θ(N²): for a million items, a
trillion steps.
Quick union
Instead of storing the set’s id directly, store a parent for each item, forming trees. An item whose parent is itself is a root, and the root names the set:
parent: 0 0 2 2 3 5 0 2 5
| |
1 3
|
4
To connect two items, find their roots and make one root the other’s child. Only one entry changes:
struct QuickUnion {
private var parent: [Int]
init(count: Int) {
parent = Array(0..<count)
}
func find(_ p: Int) -> Int {
var p = p
while parent[p] != p {
p = parent[p]
}
return p
}
mutating func connect(_ p: Int, _ q: Int) {
parent[find(p)] = find(q)
}
func isConnected(_ p: Int, _ q: Int) -> Bool {
find(p) == find(q)
}
}
var sets = QuickUnion(count: 6)
sets.connect(0, 1)
sets.connect(2, 3)
sets.connect(3, 4)
print(sets.isConnected(0, 1), sets.isConnected(1, 2), sets.isConnected(2, 4)) // true false true
Now the cost of everything is the cost of find, which is the height of the
tree. And nothing keeps the trees short. Connecting 0 to 1, then 1 to 2, then 2 to
3, and so on, builds a single path, and find(0) walks all N items. Quick union
is Θ(N) per operation in the worst case, no better than quick find.
What would Swift print?
var parent = Array(0..<5)
func find(_ p: Int) -> Int {
var p = p
while parent[p] != p { p = parent[p] }
return p
}
for i in 0..<4 {
parent[find(i)] = find(i + 1)
}
var steps = 0
var p = 0
while parent[p] != p {
p = parent[p]
steps += 1
}
print(parent, steps)Show answer and explanation
Answer[1, 2, 3, 4, 4] 4
Each connection hangs the current root under the next item, building the path 0 → 1 → 2 → 3 → 4. Finding the root of 0 takes four steps, and with N items it would take N − 1.
Weighted quick union
The fix is one decision: when connecting two trees, always put the smaller tree under the root of the larger one, measuring size by number of items. Keep a size for each root:
struct WeightedQuickUnion {
private var parent: [Int]
private var size: [Int]
init(count: Int) {
parent = Array(0..<count)
size = Array(repeating: 1, count: count)
}
func find(_ p: Int) -> Int {
var p = p
while parent[p] != p {
p = parent[p]
}
return p
}
mutating func connect(_ p: Int, _ q: Int) {
let (a, b) = (find(p), find(q))
guard a != b else { return }
if size[a] < size[b] {
parent[a] = b
size[b] += size[a]
} else {
parent[b] = a
size[a] += size[b]
}
}
func isConnected(_ p: Int, _ q: Int) -> Bool {
find(p) == find(q)
}
/// The number of steps from p to its root.
func depth(_ p: Int) -> Int {
var p = p
var steps = 0
while parent[p] != p {
p = parent[p]
steps += 1
}
return steps
}
}
var sets = WeightedQuickUnion(count: 1024)
for i in 0..<1023 {
sets.connect(i, i + 1) // the input that ruined quick union
}
print((0..<1024).map(sets.depth).max()!) // 1
The chain of connections that made quick union’s trees a path now produces a tree of height 1: every new item joins the big tree’s root directly.
In general, the height of a weighted quick union tree is at most log₂ N.
The argument is short. An item’s depth only increases when its tree is put
under another root, and that only happens when the other tree is at least as
large. So each time the item gets one level deeper, the size of its tree at
least doubles. A tree cannot double more than log₂ N times before it holds all
N items. Hence find, connect, and isConnected all take Θ(log N) time in
the worst case.
The worst case really happens: repeatedly connecting two trees of equal size (pairs, then pairs of pairs, and so on) builds a tree of height exactly log₂ N.
Path compression
One more improvement is nearly free. find walks from an item up to its root,
and every item on that path has the same root. So on the way, make each of them
point directly at the root. The next find for any of them takes one step:
mutating func find(_ p: Int) -> Int {
var root = p
while parent[root] != root {
root = parent[root]
}
var p = p
while parent[p] != root { // second pass: point everything at the root
let next = parent[p]
parent[p] = root
p = next
}
return root
}
find now changes the structure, so it becomes mutating, and so does
isConnected. The analysis is famously hard, but the result is remarkable:
with weighted union and path compression, any sequence of M operations on N
items takes O(M α(N)) time, where α is the inverse Ackermann function. It
grows so slowly that α(N) ≤ 4 for any N that could exist in this universe. In
practice, each operation is constant time, although no algorithm can make it
exactly constant.
| Implementation | connect |
isConnected |
|---|---|---|
| Quick find | Θ(N) | Θ(1) |
| Quick union | O(N) | O(N) |
| Weighted quick union | O(log N) | O(log N) |
| Weighted, with path compression | O(α(N)) amortized | O(α(N)) amortized |
Put the lines in order
Put the lines in order so the program prints 3.
let root = find(2)print(parent.filter { $0 == root }.count)func find(_ p: Int) -> Int {}parent[2] = rootparent[p] == p ? p : find(parent[p])var parent = [0, 0, 1]
Show the correct program
var parent = [0, 0, 1]
func find(_ p: Int) -> Int {
parent[p] == p ? p : find(parent[p])
}
let root = find(2)
parent[2] = root
print(parent.filter { $0 == root }.count)Lab 34: Disjoint sets
Q0: What would Swift print?
What would Swift print?
var parent = Array(0..<6)
var size = Array(repeating: 1, count: 6)
func find(_ p: Int) -> Int {
var p = p
while parent[p] != p { p = parent[p] }
return p
}
func connect(_ p: Int, _ q: Int) {
let (a, b) = (find(p), find(q))
if a == b { return }
if size[a] < size[b] { parent[a] = b; size[b] += size[a] }
else { parent[b] = a; size[a] += size[b] }
}
connect(0, 1)
connect(2, 3)
connect(3, 4)
connect(1, 4)
print(parent)Show answer and explanation
Answer[2, 0, 2, 2, 2, 5]
connect(0, 1) puts 1 under 0 (a tie keeps the first root), and 3 goes under
2, then 4 under 2. Connecting 1 and 4 joins root 0 (size 2) with root 2 (size
3), so the smaller tree, rooted at 0, goes under 2.
Q1: Counting components
Add a components property to WeightedQuickUnion: the number of disjoint
sets, kept up to date by connect in constant time.
Show solution
struct WeightedQuickUnion {
private var parent: [Int]
private var size: [Int]
private(set) var components: Int
init(count: Int) {
parent = Array(0..<count)
size = Array(repeating: 1, count: count)
components = count
}
func find(_ p: Int) -> Int {
var p = p
while parent[p] != p {
p = parent[p]
}
return p
}
mutating func connect(_ p: Int, _ q: Int) {
let (a, b) = (find(p), find(q))
guard a != b else { return }
if size[a] < size[b] {
parent[a] = b
size[b] += size[a]
} else {
parent[b] = a
size[a] += size[b]
}
components -= 1
}
}
var sets = WeightedQuickUnion(count: 10)
for (p, q) in [(0, 1), (2, 3), (1, 0), (4, 5), (3, 5)] {
sets.connect(p, q)
}
assert(sets.components == 6) // {0,1}, {2,3,4,5}, {6}, {7}, {8}, {9}Each successful connect merges two sets into one. Connecting items that are
already connected, like (1, 0), must not change the count, which is why the
guard comes first.
Q2: Checking the height bound
Build weighted quick unions of 1,024 items in three ways: a chain of connections, random connections until everything is connected, and repeatedly connecting equal-sized trees. Show that no item is ever deeper than log₂ 1024 = 10, and that the third construction reaches exactly 10.
Show solution
struct WeightedQuickUnion {
private var parent: [Int]
private var size: [Int]
init(count: Int) {
parent = Array(0..<count)
size = Array(repeating: 1, count: count)
}
func find(_ p: Int) -> Int {
var p = p
while parent[p] != p { p = parent[p] }
return p
}
mutating func connect(_ p: Int, _ q: Int) {
let (a, b) = (find(p), find(q))
guard a != b else { return }
if size[a] < size[b] { parent[a] = b; size[b] += size[a] }
else { parent[b] = a; size[a] += size[b] }
}
var height: Int {
parent.indices.map { p in
var p = p, steps = 0
while parent[p] != p { p = parent[p]; steps += 1 }
return steps
}.max()!
}
}
let n = 1024
var chain = WeightedQuickUnion(count: n)
for i in 0..<(n - 1) { chain.connect(i, i + 1) }
var random = WeightedQuickUnion(count: n)
var generator = SystemRandomNumberGenerator()
for _ in 0..<(20 * n) {
random.connect(Int.random(in: 0..<n, using: &generator), Int.random(in: 0..<n, using: &generator))
}
var balanced = WeightedQuickUnion(count: n)
var width = 1
while width < n {
for start in stride(from: 0, to: n, by: 2 * width) {
balanced.connect(start, start + width) // two trees of size `width`
}
width *= 2
}
assert(chain.height <= 10 && random.height <= 10)
assert(balanced.height == 10)Each round of the third construction pairs up trees of equal size, and each pairing puts one tree one level deeper: ten rounds, height ten. That is the worst case the proof allows, and it is reached.
Q3: Path compression
Add path compression to WeightedQuickUnion: make find mutating and point
every item on the path at the root. Then show that after one find on the
deepest item of the balanced tree from Q2, that item and every item on its path
has depth 1.
Show solution
struct UnionFind {
private var parent: [Int]
private var size: [Int]
init(count: Int) {
parent = Array(0..<count)
size = Array(repeating: 1, count: count)
}
mutating func find(_ p: Int) -> Int {
var root = p
while parent[root] != root {
root = parent[root]
}
var p = p
while parent[p] != root && p != root {
let next = parent[p]
parent[p] = root
p = next
}
return root
}
mutating func connect(_ p: Int, _ q: Int) {
let (a, b) = (find(p), find(q))
guard a != b else { return }
if size[a] < size[b] { parent[a] = b; size[b] += size[a] }
else { parent[b] = a; size[a] += size[b] }
}
mutating func isConnected(_ p: Int, _ q: Int) -> Bool {
find(p) == find(q)
}
func depth(_ p: Int) -> Int {
var p = p, steps = 0
while parent[p] != p { p = parent[p]; steps += 1 }
return steps
}
}
let n = 1024
var sets = UnionFind(count: n)
var width = 1
while width < n {
for start in stride(from: 0, to: n, by: 2 * width) {
sets.connect(start, start + width)
}
width *= 2
}
// connect's own finds have already compressed some paths; find the deepest item.
let deepest = (0..<n).max { sets.depth($0) < sets.depth($1) }!
let before = sets.depth(deepest)
_ = sets.find(deepest)
assert(before > 1 && sets.depth(deepest) == 1)
assert(sets.isConnected(0, n - 1))Note the first comment: connect calls find, so paths are already being
compressed while the tree is built, and the deepest item is not necessarily the
one from Q2. Structures that reorganize themselves as they are used are hard to
reason about exactly, which is why the α(N) analysis is so difficult, and why
their tests should check properties rather than exact shapes.
Q4: When did everyone meet?
A social network logs friendships as (time, a, b), in order of time. Write
allConnectedAt(_:people:), which returns the earliest time at which every
person is connected to every other, through chains of friends, or nil if
that never happens.
Show solution
struct UnionFind {
private var parent: [Int]
private var size: [Int]
private(set) var components: Int
init(count: Int) {
parent = Array(0..<count)
size = Array(repeating: 1, count: count)
components = count
}
mutating func find(_ p: Int) -> Int {
if parent[p] != p {
parent[p] = find(parent[p]) // recursive path compression
}
return parent[p]
}
mutating func connect(_ p: Int, _ q: Int) {
let (a, b) = (find(p), find(q))
guard a != b else { return }
if size[a] < size[b] { parent[a] = b; size[b] += size[a] }
else { parent[b] = a; size[a] += size[b] }
components -= 1
}
}
func allConnectedAt(_ log: [(time: Int, a: Int, b: Int)], people: Int) -> Int? {
var sets = UnionFind(count: people)
for entry in log {
sets.connect(entry.a, entry.b)
if sets.components == 1 {
return entry.time
}
}
return people <= 1 ? 0 : nil
}
let log = [(time: 1, a: 0, b: 1), (time: 4, a: 2, b: 3), (time: 7, a: 1, b: 0),
(time: 9, a: 3, b: 1), (time: 12, a: 4, b: 2), (time: 15, a: 0, b: 4)]
assert(allConnectedAt(log, people: 5) == 12)
assert(allConnectedAt(Array(log.prefix(4)), people: 5) == nil)The recursive find compresses the path on the way back from the recursion:
each item on the path is pointed at the root that the call below it found. It
is shorter, but recursive, so on an uncompressed chain it would be as deep as
the chain. Weighted union keeps trees at most log₂ N deep, so that is never
more than a few dozen calls.
Q5 (optional): The largest in each set
Add largest(in:), which returns the largest item in p’s set in
constant time after a find, by keeping, for each root, the largest item in
its tree, and updating it in connect.
Show solution
struct UnionFind {
private var parent: [Int]
private var size: [Int]
private var largestOfRoot: [Int]
init(count: Int) {
parent = Array(0..<count)
size = Array(repeating: 1, count: count)
largestOfRoot = Array(0..<count)
}
func find(_ p: Int) -> Int {
var p = p
while parent[p] != p { p = parent[p] }
return p
}
mutating func connect(_ p: Int, _ q: Int) {
let (a, b) = (find(p), find(q))
guard a != b else { return }
let largest = max(largestOfRoot[a], largestOfRoot[b])
if size[a] < size[b] {
parent[a] = b; size[b] += size[a]; largestOfRoot[b] = largest
} else {
parent[b] = a; size[a] += size[b]; largestOfRoot[a] = largest
}
}
func largest(in p: Int) -> Int {
largestOfRoot[find(p)]
}
}
var sets = UnionFind(count: 10)
sets.connect(1, 2)
sets.connect(6, 1)
sets.connect(9, 4)
assert(sets.largest(in: 2) == 6 && sets.largest(in: 4) == 9 && sets.largest(in: 3) == 3)Only the root’s entry needs to be right, because every query goes through
find. When two trees merge, the new root’s entry becomes the larger of the
two. The same pattern keeps any summary of a set, such as its size, its
minimum, or a sum, that can be combined from the summaries of two parts.
What’s next
Weighted quick union’s log₂ N bound came from a short argument about doubling. Next lesson: analyzing recursive functions, where the same kind of argument becomes a general method.