Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Appendix A: Complexity Cheat Sheet

Two conventions for reading these tables:

  • Average assumes random or well-distributed data. Worst is the adversarial case. Where they differ, the gap is usually the whole story. A hash table is O(1) average and O(n) worst, and which one you get depends on your hash function and your adversary.
  • ★ marks amortized bounds: cheap on average across a sequence of operations, with occasional expensive ones. A dynamic array append is O(1)★ because the resize that costs O(n) happens rarely enough to average out.

A.1 Linear Structures

StructureAccess by indexSearch by valueInsertDeleteSpace
Static arrayO(1)O(n)n/an/aO(n)
Sorted arrayO(1)O(log n)O(n)O(n)O(n)
Dynamic arrayO(1)O(n)O(1)★ at end, O(n) elsewhereO(n)O(n)
Singly linked listO(n)O(n)O(1) given the nodeO(1) given the previous nodeO(n)
Doubly linked listO(n)O(n)O(1) given the nodeO(1) given the nodeO(n)
Stackn/aO(n)O(1)★O(1)★O(n)
Queuen/aO(n)O(1)★O(1)★O(n)
DequeO(1)O(n)O(1)★ at either endO(1)★ at either endO(n)
Circular buffer (fixed capacity)O(1)O(n)O(1) at the rearO(1) at the frontO(capacity)
Bit arrayO(1)O(n/w)O(1) set a bitO(1) clear a bitn bits
Persistent vector (32-way trie)O(log₃₂ n)O(n)O(log₃₂ n) append, path copiedO(log₃₂ n) updateO(n), shared between versions
Finger treeO(log n) by index; O(1)★ at the endsO(n)O(1)★ at either endO(1)★ at either endO(n)
Gap buffer (text)O(1)O(n)O(1) at the cursor, O(distance) to move itO(1) at the cursorO(n)
Rope (text)O(log n)O(n)O(log n) anywhereO(log n) anywhereO(n)
Piece table (text, list of k pieces)O(k)O(n)O(k), text itself never movesO(k)O(n + k)

Where w = machine word size in bits.

The linked-list rows come with the caveat that makes them much less useful than they look: insertion and deletion are O(1) only once you already hold the relevant node. Getting there is O(n), so an insert-at-position is O(n) overall.

A.2 Trees and Ordered Maps

StructureSearch (avg)Search (worst)InsertDeleteSpace
BST (unbalanced)O(log n)O(n)O(log n) / O(n)O(log n) / O(n)O(n)
AVL treeO(log n)O(log n)O(log n)O(log n)O(n)
Red-black treeO(log n)O(log n)O(log n)O(log n)O(n)
Splay treeO(log n)★O(n) single opO(log n)★O(log n)★O(n)
Left-leaning red-black treeO(log n)O(log n)O(log n)O(log n)O(n)
TreapO(log n) expectedO(n)O(log n) expectedO(log n) expectedO(n)
Skip listO(log n) expectedO(n)O(log n) expectedO(log n) expectedO(n) expected
B-tree / B+ treeO(log_B n) I/OsO(log_B n) I/OsO(log_B n)O(log_B n)O(n)
Order-statistic tree (size-augmented balanced BST)O(log n) select / rankO(log n)O(log n)O(log n)O(n)
van Emde Boas tree (integer keys < u)O(log log u)O(log log u)O(log log u)O(log log u)O(u), or O(n log log u) hashed
y-fast trie (integer keys < u)O(log log u)O(log log u)O(log log u)★O(log log u)★O(n)
TrieO(L)O(L)O(L)O(L)O(N·A)
Radix / Patricia trieO(L)O(L)O(L)O(L)O(N)

Where L = key length, N = total characters stored across all keys, A = alphabet size.

On a BST of height h, successor, predecessor, floor and ceiling are O(h), and reporting every key in a range is O(h + k) for k results. A B-tree with minimum degree t has height at most log_t((n+1)/2); with t = 500, a billion keys fit in 4 levels. (Chapter 7, Chapter 10)

AVL insertion needs at most one single or double rotation, but AVL deletion may rotate at every level on the way up, O(log n) rotations. Red-black trees need at most 2 rotations per insert and 3 per delete, plus O(log n) recolourings (Chapter 8).

Two rows worth reading carefully. Skip list space is O(n) expected, not O(n log n): with promotion probability p = ½, the expected total number of nodes across all levels is 2n. The O(log n) is the expected height, which is a different quantity. And splay trees have no per-operation guarantee at all: a single access can cost O(n), and only a sequence of m operations is bounded, at O(m log n). That makes them unsuitable for latency-sensitive work regardless of their excellent amortized behavior.

A.3 Hash-Based Structures

StructureSearch (avg)Search (worst)InsertDeleteSpace
Hash table (chaining)O(1)O(n)O(1)★O(1)O(n + m)
Hash table (open addressing)O(1)O(n)O(1)★O(1)O(m)
Robin Hood hashingO(1)O(n)O(1)★O(1), backward shiftO(m)
Swiss tableO(1)O(n)O(1)★O(1)O(m) plus 1 control byte per slot
Cuckoo hashingO(1)O(1) worst caseO(1)★ expectedO(1)O(n)
Perfect hashing (static)O(1)O(1)n/an/aO(n)

Where m = number of buckets. Cuckoo hashing is the notable row: it is one of the few hash schemes with a genuine O(1) worst-case lookup, because a key can only live in one of two positions. Insertion pays for it, and can fail and require a full rehash.

Robin Hood hashing has the same average probe length as plain linear probing; what it improves is the variance, so the longest probe sequence and the cost of an unsuccessful lookup (which can stop early) drop sharply at high load. (Chapter 12)

Java’s HashMap converts a bucket to a red-black tree past 8 entries, giving O(log n) rather than O(n) in the worst case: a defense against deliberate collision flooding.

A.4 Heaps and Priority Queues

StructureFind minInsertDelete minDecrease keyMergeSpace
Binary heapO(1)O(log n)O(log n)O(log n)O(n)O(n)
Indexed binary heap (position map)O(1)O(log n)O(log n)O(log n), and O(1) to locate the itemO(n)O(n)
d-ary heapO(1)O(log_d n)O(d·log_d n)O(log_d n)O(n)O(n)
Binomial heapO(log n)O(1)★O(log n)O(log n)O(log n)O(n)
Fibonacci heapO(1)O(1)O(log n)★O(1)★O(1)O(n)
Pairing heapO(1)O(1)O(log n)★o(log n)★, exact bound openO(1)O(n)

Building a heap from n existing elements is O(n), not O(n log n): Floyd’s bottom-up heapify. This surprises people and is worth remembering.

The pairing heap’s decrease-key is known to be Ω(log log n)★ (Fredman, 1999) and o(log n)★ (Pettie’s 2005 bound is O(2^(2√(log log n)))★), but its exact cost is still an open problem.

Fibonacci heaps have the best bounds on this table and lose to binary heaps on most real workloads; see Chapter 19.

A.5 Graphs

For a graph with V vertices and E edges:

OperationAdjacency listAdjacency matrixCSR (static)
SpaceO(V + E)O(V²)O(V + E), no pointers
Add edgeO(1)O(1)O(V + E) rebuild
Check edge (u,v)O(deg(u))O(1)O(log deg(u)) if sorted
Iterate neighbors of uO(deg(u))O(V)O(deg(u)), sequential
BFS / DFSO(V + E)O(V²)O(V + E)
AlgorithmComplexityRequires
BFS / DFSO(V + E)n/a
Cycle detection (directed, three-colour DFS)O(V + E)n/a
Bipartiteness check (BFS 2-colouring)O(V + E)n/a
Topological sort (Kahn or DFS)O(V + E)DAG; Kahn also detects cycles
Strongly connected components (Kosaraju, Tarjan)O(V + E)Directed graph
0-1 BFSO(V + E)Edge weights 0 or 1
DAG shortest pathsO(V + E)DAG, any weights
Dijkstra (binary heap)O((V + E) log V)Non-negative weights
Dijkstra (Fibonacci heap)O(E + V log V)Non-negative weights
Bellman-FordO(V·E)Detects negative cycles
Floyd-WarshallO(V³)All pairs; negative edges but no negative cycles
Johnson’s algorithmO(V·E log V)All pairs, sparse graphs, negative edges
Kruskal MSTO(E log E)Union-find
Prim MST (binary heap)O(E log V)n/a
Union-Find (path compression + union by rank)O(α(n)) ★n/a
Union-Find with rollbackO(log n)No path compression

That last row is a common trap. Rollback requires undoing parent changes, which path compression makes impossible to track cheaply, so rollback DSU uses union by rank alone and costs O(log n), not O(α(n)).

α(n) is the inverse Ackermann function, below 5 for any n that fits in the observable universe.

A.6 Probabilistic and Specialized

StructureQueryInsertSpaceError
Bloom filterO(k)O(k)~1.44·log₂(1/ε)·n bitsFalse positives only
Counting Bloom filterO(k)O(k)4× a Bloom filterFalse positives only
Cuckoo filterO(1)O(1)★~(log₂(1/ε) + 3)·n bitsFalse positives; supports delete
HyperLogLogO(1)O(1)O(log log n) bits per register; 12 KB in the standard configuration~0.81% standard error with 16,384 registers (1.04/√m)
Roaring bitmapO(log c) to find the container, then O(1) or O(log 4096)O(log c), plus up to 4,096 shifted values in an array container≤ 16 bits per value within a containerNone, exact
Count-Min SketchO(k)O(k)O((1/ε)·log(1/δ))Overestimates only
Skip listO(log n) expectedO(log n) expectedO(n) expectedNone, exact

Where c = number of non-empty Roaring containers (at most 65,536 for 32-bit values).

A Bloom filter with 1% false-positive rate needs about 9.6 bits per element regardless of how large the elements are, which is the property that makes it useful.

A.7 Competitive Programming Structures

StructureBuildQueryUpdateSpace
Prefix sum arrayO(n)O(1)Rebuild O(n)O(n)
Fenwick tree (BIT)O(n)O(log n)O(log n)O(n)
Segment treeO(n)O(log n)O(log n)O(n)
Segment tree + lazy propagationO(n)O(log n)O(log n) rangeO(n)
Sparse tableO(n log n)O(1)Not supportedO(n log n)
Sqrt decompositionO(n)O(√n)O(1)O(n)
Mo’s algorithmn/aO(√n) ★ per queryn/aO(n)
Heavy-light decompositionO(n)O(log² n)O(log² n)O(n)
Link-cut treeO(n)O(log n)★O(log n)★O(n)
Wavelet treeO(n log σ)O(log σ)StaticO(n log σ)
Suffix array (SA-IS)O(n)O(m log n)StaticO(n)
Suffix automatonO(n)O(m)IncrementalO(n), ≤ 2n−1 states
Suffix treeO(n)O(m)StaticO(n)
Palindromic tree (eertree)O(n)O(1)★IncrementalO(n)
Li Chao treeO(n log C) by n insertsO(log C)O(log C)O(n)

Where σ = alphabet size, m = pattern length, C = coordinate range.

Mo’s algorithm is offline and processes q queries in O((n + q)√n) total; the O(√n) figure is the amortized per-query share, not a bound on any single query.

A.8 Array and Sequence Techniques

TechniqueTimeExtra spaceRequires
Binary search (lower / upper bound)O(log n)O(1)Sorted array
Binary search on the answerO(log R) predicate callsO(1)Monotone predicate over a range of size R
Two pointersO(n)O(1)Sorted array (for pair-sum style problems)
Sliding window (fixed or variable)O(n)O(1)Non-negative values for the variable “sum ≥ target” form
Prefix sums (1-D)O(n) build, O(1) range sumO(n)Static array
Prefix sums (2-D)O(rc) build, O(1) rectangle sumO(rc)Static r × c matrix
Difference arrayO(1) per range add, O(n) to rebuildO(n)All updates before reads
Monotonic stack (next greater element)O(n) total, amortizedO(n)n/a
Monotonic deque (sliding-window maximum)O(n) total, amortizedO(k)n/a
In-place linked-list reversalO(n)O(1)n/a
Floyd’s cycle detectionO(μ + λ)O(1)n/a
Merge sort on a linked listO(n log n)O(log n) stack, O(1) bottom-upn/a

Where μ = distance to the cycle and λ = cycle length.

String matchingPreprocessSearch a text of length nNotes
KMP (prefix function)O(m)O(n) worst caseNever backs up in the text
Z-algorithmO(n + m) totalO(n + m) worst caseSearch P + separator + T
Rabin-Karp (rolling hash)O(m)O(n + m) expectedRandom base and a large prime; verify matches to make it exact
Aho-Corasick (many patterns)O(total pattern length)O(n + number of matches)One pass for every pattern
Suffix array (search)O(n) to O(n log n) buildO(m log n) per queryIndex the text once, query many patterns
Posting-list intersection (lists of length m ≤ n)Time
Linear mergeO(m + n)
Galloping (exponential) searchO(m log(n/m))
Skip pointersBetween the two, depending on skip spacing

A.9 Caches and Load Balancing

StructurePer accessMetadata per entryScan-resistant
LRU (hash map + doubly linked list)O(1)Two pointersNo
LFU (frequency buckets)O(1)Pointers plus a countYes, but slow to forget
CLOCK (second chance)O(1) amortizedOne reference bitNo
ARCO(1)Pointers, plus ghost listsYes
W-TinyLFUO(1)Pointers, plus a shared Count-Min sketchYes
Load balancing ruleMaximum load, n requests into n servers
Uniformly randomΘ(log n / log log n) with high probability
Power of d choices (d ≥ 2)ln ln n / ln d + Θ(1) with high probability

See Chapter 29 for the simulations behind both tables.

A.10 Allocators, Clocks and Routing

Memory allocatormallocfreeFragmentation
Implicit free list, first fitO(blocks)O(1) with boundary tagsExternal; depends on placement policy
Segregated free lists (size classes)O(1) typicalO(1)Internal, bounded by class spacing (about 20% in jemalloc)
Buddy systemO(log M) splitsO(log M) mergesInternal, up to about 50% from rounding to a power of two
Slab (fixed-size objects)O(1)O(1)Little, for objects of one size
Arena / bumpO(1)Only all at onceNone until reset

Where M = the size of the managed region in units of the smallest block (Chapter 2).

Logical clockTimestamp sizeDetects concurrency?Close to wall-clock time?
Lamport clockO(1)NoNo
Vector clockO(n) for n processesYesNo
Hybrid logical clockO(1)NoYes, within the clock skew
Routing lookup (W-bit addresses, N prefixes)Memory reads per lookupMemory
Binary trieUp to WUp to 1 + N·W nodes
Multibit trie, stride k⌈W/k⌉Grows with 2^k per node (controlled prefix expansion)
DIR-24-8 (IPv4)1 for prefixes up to /24, else 232 MB first-level table plus second-level blocks
Maglev table (ECMP / load balancing)1 hash and 1 table readO(M) for a prime table size M

A.11 Complexity Growth Reference

How the classes actually behave, for intuition about when each becomes infeasible:

nO(log n)O(n)O(n log n)O(n²)O(2ⁿ)
10310331001,024
100710066410,00010³⁰
1,000101,0009,96610⁶n/a
10⁶2010⁶2×10⁷10¹²n/a
10⁹3010⁹3×10¹⁰10¹⁸n/a

Rough practical ceilings at roughly 10⁸ simple operations per second: O(n²) is fine to n ≈ 10,000; O(n log n) to n ≈ 10⁷; O(n) to n ≈ 10⁸; O(2ⁿ) to n ≈ 25; O(n!) to n ≈ 11.