Guides · Algorithms
Big-O and union-find in TypeScript
Big-O notation tells you how an algorithm slows down as its input grows. This post walks through the five growth rates you meet most, each with a short TypeScript example, then puts them to work on a classic problem: tracking which items are connected, with three versions of union-find.
gist.github.com/sawissac/3a06297363600d50b2192fa6b5fde480What Big-O measures
Big-O describes how the work an algorithm does grows with the size of its input, written n. It ignores constants and small terms, because for large inputs they stop mattering: an algorithm doing 3n + 20 steps and one doing n steps are both O(n). Both get twice as slow when the input doubles.
It usually describes the worst case. "Finding an item in an array is O(n)" means that when you're unlucky and the item is last, or missing, you look at every element.
| Notation | Name | Input doubles, work... |
|---|---|---|
| O(1) | Constant | stays the same |
| O(log n) | Logarithmic | grows by one step |
| O(n) | Linear | doubles |
| O(n²) | Quadratic | quadruples |
| O(2ⁿ) | Exponential | squares |
O(1): constant time
The work doesn't depend on the input size.
// O(1): one index lookup, however long the array is
const first = (items: number[]) => items[0];
// O(1): pop() removes the last element without touching the others
const removeLast = (items: number[]) => items.pop();Reading an index or popping the last element takes the same time whether the array holds ten items or ten million. A loop can still be O(1), as long as it runs a fixed number of times that doesn't depend on n.
O(n): linear time
The work grows in step with the input.
// O(n): the loop body runs once per element
const printAll = (items: number[]) => {
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}
};One pass, one visit per element. Summing an array, finding the largest value and items.includes(x) are all O(n).
O(log n): logarithmic time
Each step throws away a fixed fraction of what's left, usually half. Binary search on a sorted array is the standard example:
// O(log n): every pass halves the range still to search
const binarySearch = (sorted: number[], target: number) => {
let low = 0;
let high = sorted.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (sorted[mid] === target) return mid;
// target is bigger: drop the left half
if (sorted[mid] < target) low = mid + 1;
// target is smaller: drop the right half
else high = mid - 1;
}
return -1; // range is empty, target isn't there
};A million sorted items take at most 20 comparisons, because 2²⁰ is just over a million. A billion take 30. That's why logarithmic algorithms feel almost free.
A loop whose counter doubles, for (let i = 1; i < n; i *= 2), is O(log n) for the same reason.
O(n²): quadratic time
Usually a loop inside a loop over the same data.
// O(n²): n passes of the outer loop, each doing up to n more steps
const hasDuplicates = (items: number[]) => {
for (let i = 0; i < items.length; i++) {
// slice() and indexOf() both walk the rest of the array: the hidden inner loop
if (items.slice(i + 1).indexOf(items[i]) !== -1) return true;
}
return false;
};There's only one for here, but slice and indexOf each walk the rest of the array, so there's a hidden inner loop. Every element gets compared against every element after it: roughly n²/2 comparisons, which is O(n²).
The fix is often a better data structure. A Set checks membership in O(1) on average, which makes the whole thing O(n):
// O(n): one pass to build the Set; duplicates collapse, so the sizes differ
const hasDuplicates = (items: number[]) => new Set(items).size !== items.length;O(2ⁿ): exponential time
The work doubles with each extra element of input. The naive recursive Fibonacci is the classic case:
// O(2ⁿ): each call branches into two more calls
const fibonacci = (n: number): number => {
if (n <= 1) return n; // base case: fib(0) = 0, fib(1) = 1
return fibonacci(n - 1) + fibonacci(n - 2);
};Each call makes two more calls, and most of them recompute values another branch already worked out. fibonacci(30) makes about 2.7 million calls; fibonacci(50) makes about 40 billion. Remembering results you've already computed brings it down to O(n):
// O(n): each value from 2 to n is computed once, then read from the memo
const fibonacci = (n: number, memo = new Map<number, number>()): number => {
if (n <= 1) return n;
if (memo.has(n)) return memo.get(n)!; // already computed: skip the whole subtree
const value = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
memo.set(n, value); // remember it for every later call
return value;
};Dynamic connectivity
Now a problem where these growth rates decide whether a program finishes.
You have n items, numbered 0 to n - 1. You receive a stream of two kinds of request:
- union(p, q): connect item
pto itemq. - connected(p, q): are
pandqconnected, directly or through a chain of other items?
Think of computers in a network, people in a social graph, or pixels in an image. Connections are transitive: if 0 is connected to 1 and 1 to 3, then 0 is connected to 3.
A data structure that answers this is called union-find. Each version below keeps one array, id, and differs only in what the numbers in it mean.
Quick-find
Idea: id[i] is the group that i belongs to. Two items are connected when they have the same group.
function quickFind(n: number) {
// O(n): every item starts in its own group, id[i] = i
const id = Array.from({ length: n }, (_, i) => i);
// O(1): same group number means connected
const connected = (p: number, q: number) => id[p] === id[q];
// O(n): scans the whole array to relabel p's group
const union = (p: number, q: number) => {
const pGroup = id[p];
const qGroup = id[q];
for (let i = 0; i < id.length; i++) {
if (id[i] === pGroup) id[i] = qGroup;
}
};
return { id, connected, union };
}Every item starts in its own group. union moves everything in p's group into q's group:
const uf = quickFind(10);
console.log(uf.id); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
uf.union(0, 1); // [1, 1, 2, 3, 4, 5, 6, 7, 8, 9]
uf.union(2, 1); // [1, 1, 1, 3, 4, 5, 6, 7, 8, 9]
uf.union(1, 3); // [3, 3, 3, 3, 4, 5, 6, 7, 8, 9]
console.log(uf.connected(0, 3)); // true
console.log(uf.connected(0, 4)); // falseconnected is a single comparison, O(1). The problem is union: it scans the whole array every time, O(n). Connecting all n items takes n unions, so building up the structure costs O(n²). With a million items that's a trillion array accesses.
Quick-union
Idea: turn the groups into trees. id[i] is now the parent of i, and an item whose parent is itself is a root. Two items are connected when they share a root.
function quickUnion(n: number) {
// O(n): every item starts as its own root, id[i] = i
const id = Array.from({ length: n }, (_, i) => i);
// O(tree height): climb parent links until an item points at itself
const root = (i: number) => {
while (i !== id[i]) i = id[i];
return i;
};
// O(tree height): connected when both climb to the same root
const connected = (p: number, q: number) => root(p) === root(q);
// O(tree height): find both roots, then change one array entry
const union = (p: number, q: number) => {
id[root(p)] = root(q);
};
return { id, connected, union, root };
}union no longer scans the array. It changes one entry, pointing p's root at q's root:
const uf = quickUnion(10);
uf.union(0, 1); // [1, 1, 2, 3, 4, 5, 6, 7, 8, 9]
uf.union(2, 1); // [1, 1, 1, 3, 4, 5, 6, 7, 8, 9]
uf.union(1, 3); // [1, 3, 1, 3, 4, 5, 6, 7, 8, 9]
console.log(uf.root(0)); // 3 (0 → 1 → 3)
console.log(uf.connected(0, 3)); // trueThe cost moves into root, which follows parent links until it reaches the top. That's fast on a short tree, but nothing stops a tree from growing tall. Union 0 into 1, 1 into 2, 2 into 3, and so on, and you build a chain n long. Then root(0) walks all of it, so connected and union are O(n) in the worst case. Quick-union swapped one slow operation for another.
Weighted quick-union
Fix: when joining two trees, always hang the smaller tree under the root of the larger one. Track each root's tree size to know which is which.
function weightedQuickUnion(n: number) {
const id = Array.from({ length: n }, (_, i) => i);
// size[r] = number of items in the tree rooted at r
const size = new Array<number>(n).fill(1);
// O(log n): trees stay shallow because of the weighting in union
const root = (i: number) => {
while (i !== id[i]) {
id[i] = id[id[i]]; // path compression: point at the grandparent
i = id[i];
}
return i;
};
const connected = (p: number, q: number) => root(p) === root(q);
const union = (p: number, q: number) => {
const rootP = root(p);
const rootQ = root(q);
if (rootP === rootQ) return; // already in the same tree
// hang the smaller tree under the larger root
if (size[rootP] < size[rootQ]) {
id[rootP] = rootQ;
size[rootQ] += size[rootP];
} else {
id[rootQ] = rootP;
size[rootP] += size[rootQ];
}
};
return { id, connected, union, root };
}Two changes from quick-union:
- Weighting. In
union, the smaller tree goes under the larger. An item's depth only increases when its tree is merged into one at least as big, which at least doubles the size of the tree it's in. A tree ofnitems can only doublelog₂ ntimes, so no item is ever more thanlog₂ nsteps from its root. - Path compression. The line
id[i] = id[id[i]]inrootpoints each item it passes at its grandparent. Every lookup flattens the tree a little, so later lookups are faster.
The same three unions now give a flat tree:
const uf = weightedQuickUnion(10);
uf.union(0, 1); // [0, 0, 2, 3, 4, 5, 6, 7, 8, 9]
uf.union(2, 1); // [0, 0, 0, 3, 4, 5, 6, 7, 8, 9]
uf.union(1, 3); // [0, 0, 0, 0, 4, 5, 6, 7, 8, 9]Every item points straight at root 0.
Comparing them
| Algorithm | Initialise | union | connected |
|---|---|---|---|
| Quick-find | O(n) | O(n) | O(1) |
| Quick-union | O(n) | O(n)* | O(n)* |
| Weighted quick-union | O(n) | O(log n) | O(log n) |
| ...with path compression | O(n) | ≈ O(1) | ≈ O(1) |
* Worst case, when the tree degenerates into a chain.
With both weighting and path compression, the cost per operation, averaged over a long run, grows so slowly that it stays below 5 for any n you could ever store. In practice, that's constant time.
For a million items and a million unions, that's the difference between a trillion steps with quick-find and a few million with the weighted version. Same problem, same array, different meaning for the numbers in it.