Skip to content
Merged
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ cargo install mdbook && mdbook serve --open

Live-reloads at `http://localhost:3000`. Chapters live in `src/`, diagrams in `src/images/`, and the sidebar is generated from `src/SUMMARY.md`, so a new chapter needs an entry there or it won't appear.

Diagrams are inline SVG using `currentColor` for strokes and text so they work in both light and dark themes. They're pulled in with `{{#include ../images/name.svg}}` inside a `<figure>`. Two constraints: no blank lines inside an SVG file (a blank line ends the raw-HTML block in Markdown), and don't hard-code black or white.
Diagrams are inline SVG using `currentColor` for strokes and text so they work in both light and dark themes. They're pulled in with `{{#include ../images/name.svg}}` inside a `<figure>`. Three constraints: no blank lines inside an SVG file (a blank line ends the raw-HTML block in Markdown); don't hard-code black or white; and prefix every CSS class and element id with the file's name (`.btree-split-node`, not `.node`), because inline `<style>` rules apply to the whole page and two figures on one page would otherwise restyle each other. CI checks all three.

## Scope

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ A complete, free course on data structures, from asymptotic analysis and pointer

**📖 Read it online: [dnakhoa.github.io/everything-data-structures](https://dnakhoa.github.io/everything-data-structures/)**

Five volumes · 31 chapters · 4 appendices · ~185,000 words · 241 exercises with worked solutions · Python, C, C++, Java and Go examples.
Five volumes · 31 chapters · 4 appendices · ~220,000 words · 258 exercises with worked solutions · Python, C, C++, Java and Go examples.

Written by [Ngoc Anh Khoa Doan](https://github.com/dnakhoa), with the editorial help of Claude.

Expand Down
18 changes: 18 additions & 0 deletions scripts/check_book.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
3. Every chapter page starts with a single H1.
4. Code fences are balanced.
5. SVG files contain no blank lines (a blank line ends the raw-HTML block in Markdown).
Figures included on the same page must not define the same CSS class or element id,
because inline <style> rules apply to the whole page.
6. Every chapter has an Exercises section, numbered for that chapter, and every
<details> hint/solution block is balanced and padded with the blank lines
mdBook needs to render the Markdown inside it.
Expand Down Expand Up @@ -100,6 +102,22 @@ def check_svgs():
fail("%s: contains a blank line — this breaks inline embedding in Markdown" % path)
if "currentColor" not in content:
fail("%s: no currentColor — the diagram will not adapt to the dark theme" % path)
# Inline SVG styles and ids are page-global: two figures on one page must not
# share a class name or an id, or one restyles (or re-targets) the other.
for page in iter_md():
figs = re.findall(r"\{\{#include \.\./images/([\w-]+\.svg)\}\}", open(page, encoding="utf-8").read())
seen_cls, seen_id = {}, {}
for f in figs:
content = open(os.path.join(SRC, "images", f), encoding="utf-8").read()
style = re.search(r"<style>(.*?)</style>", content, re.S)
for cls in set(re.findall(r"\.([A-Za-z_][\w-]*)", style.group(1) if style else "")):
if cls in seen_cls and seen_cls[cls] != f:
fail("%s: figures %s and %s both define CSS class .%s (prefix classes with the file name)" % (page, seen_cls[cls], f, cls))
seen_cls.setdefault(cls, f)
for i in set(re.findall(r'\bid="([^"]+)"', content)):
if i in seen_id and seen_id[i] != f:
fail("%s: figures %s and %s both use id=%s" % (page, seen_id[i], f, i))
seen_id.setdefault(i, f)
print(" svgs checked")


Expand Down
32 changes: 31 additions & 1 deletion src/appendices/appendix-a-complexity-cheat-sheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ Two conventions for reading these tables:
| Deque | O(1) | O(n) | O(1)★ at either end | O(1)★ at either end | O(n) |
| Circular buffer (fixed capacity) | O(1) | O(n) | O(1) at the rear | O(1) at the front | O(capacity) |
| Bit array | O(1) | O(n/w) | O(1) set a bit | O(1) clear a bit | n bits |
| Persistent vector (32-way trie) | O(log₃₂ n) | O(n) | O(log₃₂ n) append, path copied | O(log₃₂ n) update | O(n), shared between versions |
| Finger tree | O(log n) by index; O(1)★ at the ends | O(n) | O(1)★ at either end | O(1)★ at either end | O(n) |
| Gap buffer (text) | O(1) | O(n) | O(1) at the cursor, O(distance) to move it | O(1) at the cursor | O(n) |
| Rope (text) | O(log n) | O(n) | O(log n) anywhere | O(log n) anywhere | O(n) |
| Piece table (text, list of k pieces) | O(k) | O(n) | O(k), text itself never moves | O(k) | O(n + k) |
Expand All @@ -35,6 +37,7 @@ The linked-list rows come with the caveat that makes them much less useful than
| AVL tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
| Red-black tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
| Splay tree | O(log n)★ | O(n) single op | O(log n)★ | O(log n)★ | O(n) |
| Left-leaning red-black tree | O(log n) | O(log n) | O(log n) | O(log n) | O(n) |
| Treap | O(log n) expected | O(n) | O(log n) expected | O(log n) expected | O(n) |
| Skip list | O(log n) expected | O(n) | O(log n) expected | O(log n) expected | **O(n) expected** |
| B-tree / B+ tree | O(log_B n) I/Os | O(log_B n) I/Os | O(log_B n) | O(log_B n) | O(n) |
Expand All @@ -48,6 +51,8 @@ Where **L** = key length, **N** = total characters stored across all keys, **A**

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](../volume-1/ch07-binary-search-trees.md), [Chapter 10](../volume-1/ch10-multiway-search-trees-and-b-trees.md))

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](../volume-1/ch08-self-balancing-trees.md)).

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
Expand Down Expand Up @@ -209,7 +214,32 @@ Where **μ** = distance to the cycle and **λ** = cycle length.

See [Chapter 29](../volume-5/ch29-system-design-as-data-structure-composition.md) for the simulations behind both tables.

## A.10 Complexity Growth Reference
## A.10 Allocators, Clocks and Routing

| Memory allocator | malloc | free | Fragmentation |
|------------------|--------|------|---------------|
| Implicit free list, first fit | O(blocks) | O(1) with boundary tags | External; depends on placement policy |
| Segregated free lists (size classes) | O(1) typical | O(1) | Internal, bounded by class spacing (about 20% in jemalloc) |
| Buddy system | O(log M) splits | O(log M) merges | Internal, 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 / bump | O(1) | Only all at once | None until reset |

Where **M** = the size of the managed region in units of the smallest block ([Chapter 2](../volume-1/ch02-primitive-types-and-memory-organization.md)).

| Logical clock | Timestamp size | Detects concurrency? | Close to wall-clock time? |
|---------------|----------------|----------------------|---------------------------|
| Lamport clock | O(1) | No | No |
| Vector clock | O(n) for n processes | Yes | No |
| Hybrid logical clock | O(1) | No | Yes, within the clock skew |

| Routing lookup (W-bit addresses, N prefixes) | Memory reads per lookup | Memory |
|---------------------------------------------|------------------------|--------|
| Binary trie | Up to W | Up 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 2 | 32 MB first-level table plus second-level blocks |
| Maglev table (ECMP / load balancing) | 1 hash and 1 table read | O(M) for a prime table size M |

## A.11 Complexity Growth Reference

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

Expand Down
42 changes: 42 additions & 0 deletions src/appendices/appendix-c-glossary.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@

## Structural Terms

**2-3-4 Tree**: A balanced search tree whose nodes hold one, two or three keys. A red-black tree is a binary encoding of one: each black node together with its red children is one 2-3-4 node.

**Augmented Tree**: A tree whose nodes store extra summary data about their subtrees (sizes, sums, maximums) that is kept correct through inserts, deletes and rotations. Order-statistic trees and interval trees are examples.

**Balanced Tree**: A tree whose subtree heights differ by at most a constant factor, guaranteeing O(log n) height.
Expand All @@ -34,6 +36,8 @@

**Degenerate Tree**: A tree that has degraded to essentially a linked list, the worst case for an unbalanced BST.

**Double Black**: The bookkeeping state in red-black tree deletion when removing a black node leaves one path short of a black node. The four repair cases correspond to borrowing from or merging with a sibling in the 2-3-4 view.

**Fan-out**: The number of children a node can have. High fan-out is what makes B-trees shallow.

**Fill Factor**: How full a B-tree's nodes are allowed or chosen to be. Sorted inserts leave nodes about half full; bulk loading can pack them completely.
Expand All @@ -44,6 +48,8 @@

**Leaf**: A node with no children.

**Left-Leaning Red-Black Tree**: A red-black variant (Sedgewick, 2008) in which red links may only lean left, corresponding to 2-3 trees and shortening insertion code considerably.

**Minimum Degree (t)**: The B-tree parameter that bounds node size: every node except the root holds between t − 1 and 2t − 1 keys.

**Order Statistic**: The k-th smallest element of a set. A BST augmented with subtree sizes answers select (k-th smallest) and rank (position of a key) in O(height).
Expand Down Expand Up @@ -86,14 +92,22 @@

## Memory and Storage

**Arena (Bump Allocator)**: An allocator that hands out memory by advancing a pointer through a large block and frees everything at once. O(1) allocation, no per-object free; used by compilers and per-request memory pools.

**Bit-Packing**: Storing a block of small integers in exactly as many bits each as the largest needs. With delta encoding, the basis of posting-list compression in search engines.

**Boundary Tag**: A size-and-status field stored at both ends of a heap block, so the allocator can find and merge a free neighbour in O(1) when a block is freed.

**Buddy Allocator**: An allocator that splits memory into power-of-two blocks and merges a freed block with its "buddy", found by flipping one address bit. The Linux page allocator uses it.

**Cache Line**: The unit of transfer between memory and cache, typically 64 bytes. Reading one byte costs the same as reading its whole line.

**Cache-Oblivious**: Achieving optimal I/O performance without knowing the block size. By being well-organized at every scale simultaneously.

**External Memory Model**: A cost model counting block transfers rather than operations. Predicts real disk performance where the RAM model does not.

**Fragmentation**: Memory that is free but unusable. *Internal* fragmentation is wasted space inside allocated blocks (rounding up); *external* fragmentation is free space split into pieces too small to satisfy a request.

**Gap Buffer**: A text buffer that keeps one contiguous gap at the cursor, so typing is O(1) but moving the cursor far away costs a large copy. Used by Emacs.

**Locality**: The tendency of an access pattern to touch nearby addresses. Sequential access has good locality; pointer chasing has none.
Expand All @@ -106,6 +120,10 @@

**Segment (search index)**: An immutable chunk of an inverted index. New documents create new segments, deletions are marked in a bitset, and background merges combine segments, much like LSM-tree compaction.

**Size Class**: One of a fixed set of block sizes an allocator rounds requests up to, each with its own free list. The basis of jemalloc, tcmalloc and glibc's bins.

**Slab Allocator**: An allocator that keeps caches of same-sized, pre-initialized objects carved from pages. Introduced by Bonwick in 1994; Linux's SLUB is a descendant.

**Varint (Variable-Byte Encoding)**: Encoding an integer in 7-bit groups, one per byte, with the high bit marking that more bytes follow. Small numbers take one byte.

**Write Amplification**: The ratio of bytes actually written to storage versus bytes logically written by the application.
Expand All @@ -114,10 +132,16 @@

**ABA Problem**: A compare-and-swap succeeds because a pointer's value is unchanged, even though the state it refers to has changed and changed back. Defended against with tagged pointers or hazard pointers.

**Banker's Queue**: Okasaki's persistent queue, which keeps amortized O(1) operations even when old versions are reused by scheduling the expensive list reversal lazily and memoizing it.

**CAS (Compare-and-Swap)**: An atomic hardware instruction that sets a memory location to a new value only if it currently holds an expected one. The universal primitive for lock-free programming.

**Copy-on-Write**: Sharing data until a write occurs, at which point the written portion is duplicated.

**Fat Node**: A persistence technique that stores every historical value of a field, stamped with its version, inside the node itself. Updates cost O(1) space; reads pay a search over the stamps.

**Finger Tree**: A persistent sequence with amortized O(1) access at both ends and O(log n) split and concatenation. Annotating it with a monoid yields indexed sequences, priority queues and interval trees from one structure.

**Linearizability**: Every operation appears to take effect instantaneously at some moment between its call and return, consistent with real time. The standard correctness condition for concurrent objects, and notable for composing.

**Lock-Free**: Guaranteeing that *some* thread always makes progress. Weaker than **wait-free**, which guarantees *every* thread finishes in bounded steps.
Expand All @@ -128,6 +152,8 @@

**Persistent**: Preserving previous versions after modification. *Partial* persistence allows querying old versions; *full* allows updating them; *confluent* allows merging them. Unrelated to durable storage.

**Persistent Vector**: A persistent array stored as a wide trie (typically 32-way) indexed by groups of bits of the position. Updates copy one root-to-leaf path, O(log₃₂ n). Used by Clojure and Scala.

**Structural Sharing**: Reusing unchanged subtrees between versions of an immutable structure. What makes persistence affordable.

## Distributed Systems
Expand All @@ -142,8 +168,18 @@

**DHT (Distributed Hash Table)**: A hash table partitioned across many machines, with a routing protocol for locating the responsible node.

**ECMP (Equal-Cost Multipath)**: Spreading traffic across several equally good next hops by hashing each flow's header fields, so that packets of one flow stay on one path and are not reordered.

**Eventual Consistency**: A guarantee that replicas converge given no further updates, with no bound on when.

**Happens-Before**: The causal order of events in a distributed system: a precedes b if they are on the same process in that order, or a message chain connects them. Events not ordered either way are concurrent.

**Hybrid Logical Clock (HLC)**: A timestamp that stays close to physical time but, like a Lamport clock, never violates causality. Used by CockroachDB.

**Lamport Clock**: A per-process counter incremented on each event and advanced past any timestamp received in a message. If a happens before b then L(a) < L(b), but not conversely.

**Maglev Hashing**: Google's consistent hashing scheme for load balancers: each backend fills a prime-sized lookup table in its own permutation order, giving near-perfect balance and little remapping when a backend changes.

**Merkle Tree**: A tree of hashes where each node hashes its children, allowing two large datasets to be compared (and their differences located) in logarithmic work.

**Power of Two Choices**: Sending each request to the less loaded of two randomly chosen servers. Cuts the maximum load from Θ(log n / log log n) to Θ(log log n) and avoids the herding that "least loaded" suffers with stale data.
Expand All @@ -152,6 +188,8 @@

**Scan Resistance**: A cache policy's ability to survive a one-off sequential scan without evicting its genuinely popular items. LRU has none; LFU, ARC and W-TinyLFU do.

**Sequence CRDT**: A replicated list or text that gives every element a unique, ordered identifier so concurrent inserts and deletes converge. RGA, used in Automerge, is one example.

**Vector Clock**: A per-replica counter vector that distinguishes causally-ordered updates from genuinely concurrent ones.

## Probabilistic and Compressed
Expand All @@ -172,10 +210,14 @@

**Border**: A string that is both a proper prefix and a suffix of another. The prefix function (KMP's failure function) records the longest border of each prefix of a pattern.

**Controlled Prefix Expansion**: Rewriting routing prefixes whose length is not a multiple of a trie's stride into several longer prefixes that are, so a multibit trie can consume several address bits per memory access.

**Inverted Index**: A map from each term to its posting list, the sorted list of documents containing it. The core structure of full-text search.

**LCP Array**: Longest Common Prefix between each pair of adjacent suffixes in a suffix array. Together they encode a suffix tree implicitly.

**Longest-Prefix Match**: The IP routing lookup: among all table prefixes matching an address, choose the longest, because it is the most specific route.

**MBR (Minimum Bounding Rectangle)**: The smallest axis-aligned rectangle enclosing a set of objects. The key type in an R-tree, and overlap between sibling MBRs is what degrades R-tree queries.

**Posting List**: The sorted list of document IDs (plus frequencies or positions) for one term in an inverted index. Stored as compressed gaps between consecutive IDs.
Expand Down
Loading
Loading