Foundations of ComputingVol. 1 · Part I
0 / 0

Shelves / Foundations of Computing

CS·03

Data Structures

How data is laid out in memory and what each layout makes cheap or expensive, from arrays and hash tables to B+ trees, Bloom filters and LSM trees.

62 topics · ~77 min read · 40-question quiz
Updated Suggest a correction

Start here: organising data

What a data structure is

A data structure is a way of organising many values so that the operations you need are fast. The same 10,000 customer records can be kept in many arrangements, and each arrangement makes some questions cheap and others expensive:

  • Kept in arrival order, "who came first?" is instant, but "is customer 4,821 here?" means checking one by one.
  • Kept sorted by id, finding customer 4,821 takes a dozen steps (open in the middle, go left or right, repeat), but inserting a new customer means shifting others to make room.
  • Kept in a hash table, "is customer 4,821 here?" takes about one step, but "list them in order" needs extra work.

Real life is full of data structures. A library shelves books by a call number so you can find one quickly; a dictionary (the book) is sorted alphabetically; a queue at a counter serves people in arrival order; a pile of plates gives you the top one. Choosing a data structure means asking: which operations will this program do most often, and how big will the data get?

Memory as a row of numbered boxes

To understand why some operations are fast, picture memory (chapter 1) as an enormous row of numbered boxes, each holding one byte. The number of a box is its address. The computer can jump to any address directly, as quickly as to any other: that's what "random access" means.

  • If 100 numbers sit in consecutive boxes, finding the 57th is arithmetic: start address + 57 × (size of one number). One step, whatever the position.
  • If each number sits somewhere different, with a note saying where the next one is, finding the 57th means following 57 notes.

Those two pictures are the two fundamental ways to organise data: contiguous (side by side: arrays) and linked (scattered, connected by addresses called pointers or references). Every other structure is built from them.

The essential structures, in everyday terms

array: numbered lockers 01234 linked list: a treasure hunt ABC stack: pile of plates ← top queue: line at a counter ↑ frontback ↑ hash table: coat check "dal" hash slot 7: 90 tree: folders inside folders root graph: a city map
Six core data structures as everyday objects. An array is a row of numbered lockers; a linked list is a treasure hunt where each clue says where the next is; a stack is a pile of plates; a queue is a line at a counter; a hash table is a coat check that turns your ticket into a hook number; a tree is a folder hierarchy.
  • Array (Python list, Java ArrayList, Go slice, C++ vector, Rust Vec): values side by side, numbered from 0. Reading or writing position i is instant. Adding at the end is usually instant. Inserting or deleting in the middle means shifting everything after it.
  • Linked list: each value sits in its own node with a pointer to the next node, like a treasure hunt where each clue tells you where the next one is. Inserting next to a node you already have is instant (change two pointers); finding the 57th item means following 57 pointers.
  • Stack: you only add and remove at the top, so the last thing in is the first out (LIFO). Undo history, the browser's back button, and the call stack that tracks which function called which (chapter 2).
  • Queue: add at the back, remove from the front: first in, first out (FIFO). Print jobs, orders waiting for a kitchen, messages waiting to be processed. A deque (double-ended queue) allows both ends.
  • Hash table (dictionary, map, set): a hash function turns the key ("dal") into a slot number, like a coat check turning your ticket into a hook. Finding, adding and removing by key are about one step, however many items there are. The price: no useful order, and some extra memory.
  • Tree: items arranged in levels, each with children, like folders inside folders or a family tree. A binary search tree keeps smaller values to the left and larger to the right, so finding a value means going left or right at each level: about 20 steps for a million items, and items stay in sorted order. Databases use a wide variant called the B-tree (this chapter's lab measures one).
  • Heap / priority queue: always gives you the most urgent item next, like a hospital triage desk, without sorting everything.
  • Graph: points (nodes) connected by links (edges), like towns and roads or people and friendships. Used for maps, networks, dependencies (chapter 4's algorithms find routes through them).

These run in every language. In Python:

Python
from collections import deque
import heapq, time

undo = []                                   # a stack: last in, first out
undo.append("type 'H'"); undo.append("type 'i'"); undo.append("make bold")
print("undo stack, top is last:", list(undo), "→ undo:", undo.pop())

orders = deque()                            # a queue: first in, first out
orders.append("order 101"); orders.append("order 102"); orders.append("order 103")
print("queue → serve:", orders.popleft(), "| still waiting:", list(orders))

prices = {"biryani": 180, "dal": 90, "paneer": 160}   # a dictionary (hash table)
prices["rajma"] = 110
print("price of dal:", prices["dal"], "| has 'pizza'?", "pizza" in prices)

tasks = []                                  # a priority queue (heap): lowest number = most urgent
heapq.heappush(tasks, (3, "reply to email")); heapq.heappush(tasks, (1, "kitchen fire")); heapq.heappush(tasks, (2, "late delivery"))
print("most urgent:", heapq.heappop(tasks)[1], "| next:", heapq.heappop(tasks)[1])

ids = list(range(1_000_000)); id_set = set(ids)       # is a value present? list vs set
t = time.perf_counter(); found = 999_999 in ids; list_time = time.perf_counter() - t
t = time.perf_counter(); found = 999_999 in id_set; set_time = time.perf_counter() - t
print(f"membership test in 1,000,000 items: list {list_time * 1e3:.2f} ms, set {set_time * 1e6:.2f} µs")
Text
undo stack, top is last: ["type 'H'", "type 'i'", 'make bold'] → undo: make bold
queue → serve: order 101 | still waiting: ['order 102', 'order 103']
price of dal: 90 | has 'pizza'? False
most urgent: kitchen fire | next: late delivery
membership test in 1,000,000 items: list 7.78 ms, set 3.37 µs

The last line is the whole chapter in one measurement: asking "is 999,999 present?" took over 2,000 times longer with a list (checking a million items one by one) than with a set (one hash lookup). Same data, same question, different structure.

Counting steps: a first look at Big-O

Programmers describe how an operation's cost grows with the amount of data, n, using Big-O notation (chapter 4 makes it precise):

Notation Name Meaning Everyday example
O(1) Constant Same number of steps however big n is Opening locker 57 directly
O(log n) Logarithmic Steps grow by one each time n doubles Finding a word in a dictionary by halving
O(n) Linear Steps grow in proportion to n Checking every item in a list
O(n log n) "n log n" A bit more than linear Good sorting
O(n²) Quadratic Doubling n quadruples the work Comparing every pair of items

How the main structures compare for common operations (typical cases):

Operation Array Linked list Hash table Balanced tree
Get item by position O(1) O(n) – O(log n)
Find by value or key O(n) (O(log n) if sorted) O(n) O(1) O(log n)
Add at end O(1) on average O(1) with a tail pointer O(1) on average O(log n)
Insert/delete in the middle O(n) O(1) once you're there O(1) O(log n)
Keep items in sorted order Costly Costly No Yes

Choosing a structure

A decision guide that covers most everyday cases:

  • Need items in order and access by position? An array/list.
  • Need to look things up by a key (id, name)? A hash map. Need to know whether something is present? A hash set.
  • Need lookups and sorted order or ranges ("all orders between 10:00 and 11:00")? A balanced tree (Java TreeMap, C++ std::map, Rust BTreeMap) or a sorted array.
  • Need last in, first out? A stack. First in, first out? A queue. Most urgent first? A priority queue (heap).
  • Modelling connections? A graph.

Check yourself

How deep to go in data structures

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere and L4 in the labs at the end, which is the foundation every later volume builds on.

Level What you can do
L1 Name the structures and their headline costs (array O(1) index, hash O(1) average, tree O(log n))
L2 Use each language's standard collections correctly and pick the right one for common cases
L3 Explain memory layout, cache behaviour, resizing, collision handling, rebalancing, and why B+ trees and LSM trees suit storage
L4 Diagnose pathological behaviour: hash flooding, resize spikes, pointer-chasing slowness, unbounded growth
L5 Choose and combine structures for a workload (read/write mix, size, ordering, concurrency, memory budget)
L6 Run data-structure-heavy systems in production: memory footprint at scale, latency tails, persistence and recovery

The cost model behind every data structure

Abstract operations and real machines

A data structure is a way of arranging data in memory so that certain operations are cheap. No structure makes everything cheap. Each one is a set of trade-offs between lookup, insertion, deletion, ordering, memory use and cache behaviour. An abstract data type (ADT) says what operations exist (a "map" has get, put, remove). A data structure is how they're implemented (hash table, red-black tree, B-tree, skip list).

Textbooks analyse structures in the RAM model: every memory access costs 1. Real machines don't work that way. Chapter 7 explains the details, but you need the headline numbers now, because they decide which structure wins in practice:

Operation Approximate latency Relative to L1
L1 cache hit ~1 ns (4 cycles) 1×
L2 cache hit ~3–4 ns 4×
L3 cache hit ~10–15 ns 12×
Main memory (DRAM) ~60–100 ns ~80×
NVMe SSD random read ~20–100 µs ~50,000×
Network round trip in a datacentre ~200–500 µs ~300,000×

Memory moves in cache lines of 64 bytes. When you read one int, the 15 next to it arrive for free, and the hardware prefetcher notices sequential patterns and fetches ahead. So:

  • Walking an array sequentially costs about one miss per 64 bytes, and the prefetcher hides most of those.
  • Walking a linked list costs roughly one full miss per node, because each node is somewhere random and the next address isn't known until the current node arrives. This is called pointer chasing.

That's why an O(n) array scan often beats an O(log n) tree lookup for small n, and why B-trees beat binary trees. Keep both models in mind: big-O tells you how cost grows, and the memory hierarchy tells you the constant.

Complexity cheat sheet

Structure Access by index Search Insert Delete Ordered? Memory
Array (static) O(1) O(n), O(log n) sorted — — If you sort it Tight
Dynamic array O(1) O(n) O(1)* at end, O(n) middle O(1) end, O(n) middle No ~1–2× slack
Linked list O(n) O(n) O(1) given node O(1) given node Insertion order +1–2 pointers/node
Hash table — O(1) avg, O(n) worst O(1)* avg O(1) avg No Load factor slack
Balanced BST (AVL/RB) O(log n) with augmentation O(log n) O(log n) O(log n) Yes 2–3 pointers + colour/height
B-tree / B+ tree — O(log n), few cache misses O(log n) O(log n) Yes Dense nodes
Binary heap — O(n) O(log n) O(log n) min/max Partial Tight (array)
Trie — O(key length) O(key length) O(key length) Lexicographic Can be large
Skip list — O(log n) expected O(log n) expected O(log n) expected Yes ~2 pointers/node avg

* amortised: occasionally O(n), but O(1) on average over any sequence. Chapter 4 defines this precisely.

Arrays

Contiguous memory and O(1) indexing

An array stores n elements of the same size back to back. Element i lives at a computable address:

Text
address(a[i]) = base + i × sizeof(element)

The CPU computes this with one multiply-add, often folded into the load instruction itself (mov eax, [rdi + rsi*4]). That's why indexing is O(1) regardless of i, and why arrays are 0-indexed in C: the index is the offset.

a[0]=7 a[1]=2 a[2]=9 a[3]=4 a[4]=1 a[5]=8 0x10000x10040x10080x100C0x10100x1014 base = 0x1000, element size = 4 bytes
An int array of 6 elements starting at address 0x1000. Each element is 4 bytes, so a[3] is at 0x1000 + 3×4 = 0x100C.

Two consequences follow:

  • Bounds: nothing in the address formula stops i from being 1,000,000. C doesn't check. The other five languages check on every access, though an optimiser removes checks it can prove redundant (iterating for x in v in Rust has no per-element check).
  • Fixed size: the next element's slot may already belong to something else, so an array can't grow in place.

Insertion and deletion cost

Inserting at position i means shifting elements i … n−1 one slot right, which is O(n − i). Deleting shifts them left. At the end it's O(1). Two tricks avoid shifting when order doesn't matter:

  • Swap-remove: overwrite the element to delete with the last element, then shrink by one. That's O(1), but it reorders. Rust has Vec::swap_remove, Zig has swapRemove, and C++ has the erase-remove idiom with std::swap.
  • Tombstones / lazy deletion: mark a slot dead and compact later.

Even the O(n) shift is fast in practice, because memmove copies contiguous memory at tens of GB/s. Inserting into the middle of a 1,000-element vector is usually faster than inserting into a linked list, which has to find the position first by pointer chasing.

Dynamic arrays and amortised growth

A dynamic array (std::vector, ArrayList, Vec, Go slice, Zig ArrayList) wraps a heap buffer with two numbers: length (elements in use) and capacity (slots allocated). Appending writes to slot len if len < cap. Otherwise it allocates a bigger buffer, copies everything over, frees the old one, then appends.

The growth policy is critical. If capacity grows by a constant (+10), n appends cost O(n²) total. If it grows by a factor (×1.5 or ×2), the total copying across n appends is at most about 2n (or 3n for ×1.5), so each append is amortised O(1).

Text
appends:   1   2   3   4   5   6   7   8   9 …
capacity:  1   2   4   4   8   8   8   8  16 …
copies:    0   1   2   0   4   0   0   0   8 …   total copies < 2n

Growth factors in practice:

Implementation Growth
libstdc++ / libc++ std::vector ×2
MSVC std::vector ×1.5
Java ArrayList ×1.5 (old + old >> 1)
Rust Vec ×2 (with a minimum of 4 or 8 for small elements)
Go slices (append) ×2 below 256 elements, then gradually towards ×1.25
Zig ArrayList grows by about ×1.5 plus a constant (ensureTotalCapacity uses a "better capacity" rule)

A factor below the golden ratio (~1.618) has a subtle benefit: freed blocks can eventually be reused for a later, larger allocation. With ×2, the sum of all previous blocks is always smaller than the next request.

#include <stdlib.h>
#include <string.h>

typedef struct { int *data; size_t len, cap; } IntVec;

int intvec_push(IntVec *v, int x) {
    if (v->len == v->cap) {
        size_t ncap = v->cap ? v->cap * 2 : 4;
        int *nd = realloc(v->data, ncap * sizeof *nd);   // may move the buffer
        if (!nd) return -1;                              // old buffer still valid
        v->data = nd;
        v->cap = ncap;
    }
    v->data[v->len++] = x;
    return 0;
}

int intvec_insert(IntVec *v, size_t i, int x) {       // O(n - i)
    if (intvec_push(v, 0) != 0) return -1;            // grow by one
    memmove(&v->data[i + 1], &v->data[i], (v->len - 1 - i) * sizeof *v->data);
    v->data[i] = x;
    return 0;
}
void intvec_free(IntVec *v) { free(v->data); *v = (IntVec){0}; }

Cache locality

Locality of reference has two parts. Spatial locality means that after touching address x, you'll likely touch x+1 soon. Temporal locality means that after touching x, you'll likely touch x again soon. Arrays maximise spatial locality. You can measure the effect directly:

C
// Summing 10 million ints. Same O(n) work, very different speed.
long sum_array(const int *a, size_t n) { long s = 0; for (size_t i = 0; i < n; i++) s += a[i]; return s; }
long sum_list(const Node *p)           { long s = 0; for (; p; p = p->next) s += p->value; return s; }
// Typical result: array ~3–5 ms (memory-bandwidth bound, SIMD-vectorised);
// list with nodes scattered in memory ~50–100+ ms (one cache miss per node).

Java adds another layer. A List<Integer> is an array of pointers to boxed Integer objects scattered across the heap, so summing it is pointer chasing even though ArrayList is "an array." An int[] is truly contiguous. This difference is one of the largest everyday performance traps in Java.

Multi-dimensional arrays

A 2-D array m[rows][cols] must be flattened into 1-D memory. Row-major order stores each row contiguously (C, C++, Rust arrays, Zig, Go, NumPy's default), so m[r][c] is at base + (r × cols + c) × size. Column-major order stores columns contiguously (Fortran, MATLAB, R, Julia, most BLAS libraries).

Loop order must match the layout:

C
// row-major: iterate rows outer, columns inner → sequential access
for (int r = 0; r < N; r++) for (int c = 0; c < N; c++) sum += m[r][c];   // fast
for (int c = 0; c < N; c++) for (int r = 0; r < N; r++) sum += m[r][c];   // stride N: ~5–10× slower for large N

Java has no true 2-D arrays. int[][] is an array of references to separate int[] rows (a jagged array), each a separate heap object that may have a different length. For performance-critical matrices, use one flat int[rows * cols]. Go's [][]int is also jagged, a slice of slices, while [R][C]int is contiguous.

Linked structures

Singly linked lists

A singly linked list is a chain of nodes, each holding a value and a pointer to the next node. The list itself is a pointer to the head (and sometimes the tail and a length).

head 3● 7● 1● null value | next
A singly linked list holding 3, 7, 1. Each node is a separate allocation; the last next pointer is null.

Operation costs:

  • Push or pop at the head: O(1). Allocate a node and point it at the old head.
  • Append at the tail: O(1) if you keep a tail pointer, otherwise O(n).
  • Insert or delete after a known node: O(1), relinking two pointers. That's the main selling point.
  • Find by value or index: O(n), with pointer chasing.
  • Delete a known node: O(n) in a singly linked list, because you need its predecessor. The pointer-to-pointer trick handles all cases uniformly.
#include <stdlib.h>
typedef struct Node { int value; struct Node *next; } Node;

void push_front(Node **head, int v) {
    Node *n = malloc(sizeof *n);
    n->value = v;
    n->next = *head;
    *head = n;
}

// Linus's "good taste" deletion: a pointer to the link that points at the node,
// so deleting the head needs no special case.
void remove_value(Node **head, int v) {
    for (Node **link = head; *link; link = &(*link)->next) {
        if ((*link)->value == v) {
            Node *dead = *link;
            *link = dead->next;
            free(dead);
            return;
        }
    }
}

Node *reverse(Node *h) {          // classic interview question: three pointers
    Node *prev = NULL;
    while (h) { Node *next = h->next; h->next = prev; prev = h; h = next; }
    return prev;
}

Doubly linked lists and sentinels

A doubly linked list adds a prev pointer to each node. Now you can delete any node in O(1) given only a pointer to it, and you can walk in both directions. The cost is one more pointer per node and two pointer updates per operation.

A sentinel (dummy) node removes edge cases. Make the list circular around a permanent dummy node, so that every real node always has a non-null prev and next, and insert and delete never test for "is this the head?":

C
typedef struct DNode { struct DNode *prev, *next; int value; } DNode;

void list_init(DNode *s) { s->prev = s->next = s; }              // empty: sentinel points to itself
void insert_after(DNode *pos, DNode *n) {
    n->prev = pos; n->next = pos->next;
    pos->next->prev = n; pos->next = n;
}
void unlink_node(DNode *n) { n->prev->next = n->next; n->next->prev = n->prev; }  // no branches!

The classic application is an LRU cache: a hash map from key to list node, plus a doubly linked list ordered by recency. A hit moves the node to the front in O(1), and eviction removes the tail in O(1). Java's LinkedHashMap with accessOrder = true is this structure; override removeEldestEntry to make an LRU cache in a few lines.

Circular lists and intrusive lists

A circular list links the last node back to the first. It's useful for round-robin scheduling (keep a cursor and advance it forever) and ring-shaped problems such as the Josephus problem. The sentinel list above is circular.

An intrusive list puts the link fields inside your own struct instead of wrapping your data in a node. The Linux kernel's struct list_head is the famous example: one struct can sit on several lists at once (embed several list_heads), and moving it between lists needs no allocation. The container_of macro recovers the containing struct from a pointer to its link field by subtracting the field's offset. Zig 0.15's standard linked lists are intrusive for the same reasons.

When to use a linked list

Rarely, because of cache misses. Real uses are:

  • O(1) splicing or removal given a node pointer you already hold: LRU caches, schedulers' run queues, free lists in allocators.
  • Lock-free stacks and queues, where atomically swapping one pointer is the key operation (chapter 8).
  • Persistent (immutable) lists in functional languages, where cons shares the tail.
  • When elements can't move in memory, because something holds pointers to them.

Bjarne Stroustrup's well-known benchmark showed std::vector beating std::list for insert-in-sorted-position at every size, because the linear search to find the position dominates and vectors search much faster.

Stacks and queues

Stack

A stack is last-in, first-out (LIFO), with push, pop and peek, all O(1). Implement it as a dynamic array that pushes and pops at the end. Stacks appear everywhere:

  • The call stack (chapter 7): each function call pushes a frame.
  • Undo history, browser back buttons.
  • Parsing: matching brackets, evaluating expressions (the shunting-yard algorithm converts infix to postfix), and interpreters' operand stacks. The JVM is a stack machine: iadd pops two ints and pushes their sum.
  • DFS with an explicit stack instead of recursion (chapter 2).
  • Monotonic stacks: "next greater element" in O(n).
Rust
fn balanced(s: &str) -> bool {
    let mut st = Vec::new();
    for c in s.chars() {
        match c {
            '(' | '[' | '{' => st.push(c),
            ')' => if st.pop() != Some('(') { return false },
            ']' => if st.pop() != Some('[') { return false },
            '}' => if st.pop() != Some('{') { return false },
            _ => {}
        }
    }
    st.is_empty()
}

Queue and the ring buffer

A queue is first-in, first-out (FIFO): enqueue at the back and dequeue from the front. A naive array queue that shifts on dequeue is O(n). The fix is a ring buffer (circular buffer): a fixed array with a head index and a tail index that wrap around.

C D E A B 01234567 head=6 tail=3 dequeue order: A, B, C, D, E (wraps from index 7 to 0)
A ring buffer of capacity 8 holding 5 items. head is where the next dequeue reads; tail is where the next enqueue writes. Both wrap modulo 8.
C
#define CAP 8                      // power of two so `& (CAP-1)` replaces `% CAP`
typedef struct { int buf[CAP]; unsigned head, tail; } Ring;   // head/tail count forever

int ring_push(Ring *r, int x) {
    if (r->tail - r->head == CAP) return -1;        // full (unsigned subtraction handles wrap)
    r->buf[r->tail++ & (CAP - 1)] = x;
    return 0;
}
int ring_pop(Ring *r, int *out) {
    if (r->tail == r->head) return -1;               // empty
    *out = r->buf[r->head++ & (CAP - 1)];
    return 0;
}

The trick of letting head and tail count up forever and masking on access avoids the classic ambiguity: with wrapped indices, head == tail could mean either empty or full. Ring buffers back network card queues, audio pipelines, logging, Go's buffered channels, the LMAX Disruptor, and Linux io_uring's submission and completion queues.

Deque

A deque (double-ended queue, "deck") supports O(1) push and pop at both ends. It's usually a ring buffer that can grow (Java ArrayDeque, Rust VecDeque, Python collections.deque). C++ std::deque is different: a map of fixed-size blocks, so references stay valid when you push at either end, but iteration is slower. Deques support sliding-window algorithms (the monotonic deque gives sliding-window maximum in O(n)), 0-1 BFS, and work-stealing schedulers, where a thread pops its own work from one end while thieves steal from the other. Java's ForkJoinPool, Go's scheduler, Tokio and Rayon all use work stealing.

Use ArrayDeque, not Stack or LinkedList, in Java. Stack extends the synchronised Vector, and both legacy classes are slower.

Priority queue

A priority queue always returns the highest-priority item next, not the oldest. It's an ADT, usually implemented as a binary heap (covered below). It underlies Dijkstra's algorithm, A search, event-driven simulations, schedulers, top-k queries, merging k* sorted lists, and timer wheels.

Standard library map

ADT C++ Java Rust Go Zig
Stack std::stack / vector ArrayDeque Vec slice ArrayList
Queue std::queue ArrayDeque VecDeque slice or buffered channel ring buffer over a slice
Deque std::deque ArrayDeque VecDeque — (write one) —
Priority queue std::priority_queue (max) PriorityQueue (min) BinaryHeap (max) container/heap (interface) std.PriorityQueue (comparator)
Concurrent queue (libs: moodycamel) ConcurrentLinkedQueue, ArrayBlockingQueue crossbeam / std::sync::mpsc channels std.Thread + mutex

Hashing and hash tables

Hash functions

A hash table answers "what value goes with key k?" in O(1) on average. It works by turning the key into an array index with a hash function: index = hash(k) mod capacity. A good hash function for tables must be:

  1. Deterministic: the same key always gives the same hash, within one process at least.
  2. Uniform: keys spread evenly over the output range, so similar keys ("user1", "user2") land far apart. This is the avalanche property: flipping one input bit flips about half the output bits.
  3. Fast: it runs on every lookup.
  4. Consistent with equality: if a == b then hash(a) == hash(b). The reverse doesn't need to hold, because collisions are allowed.

Common choices:

Hash Used by Notes
FNV-1a Simple tables, C code Tiny and fast for short keys; weak avalanche
SipHash-1-3 / 2-4 Rust HashMap default, Python, Perl Keyed with a random seed per process; resists HashDoS
wyhash, rapidhash Zig std.HashMap (wyhash), Go (AES-based or wyhash-style runtime hash) Very fast, good quality
xxHash, MurmurHash3 Databases, Kafka partitioner (murmur2), Cassandra (Murmur3) Fast, non-cryptographic
Java hashCode() Java collections Defined per class. String uses s[0]·31^(n-1) + … + s[n-1]. HashMap then mixes the top bits down: h ^ (h >>> 16)
SHA-256, BLAKE3 Content addressing, integrity (Git, Merkle trees) Cryptographic: collision-resistant but too slow for tables

Non-cryptographic hashes aim for speed and spread. Cryptographic hashes also make it infeasible to find collisions on purpose.

Collisions, buckets and load factor

Two different keys mapping to the same index is a collision. By the birthday paradox, collisions are unavoidable: with 365 buckets, two of only 23 random keys share a bucket with probability above 50%. So every hash table needs a collision strategy, and every table watches its load factor:

Interactive diagram: A hash table: buckets, collisions and growing. It needs JavaScript; the text around it says the same.
Text
load factor α = number of entries / number of buckets

As α grows, collisions grow and operations slow down. When α crosses a threshold, the table resizes: it allocates about twice as many buckets and rehashes every entry into its new position. This is O(n), but it happens rarely enough to be amortised O(1), exactly like dynamic array growth.

Table Max load factor before resize
Java HashMap 0.75
C++ std::unordered_map 1.0 (configurable max_load_factor)
Rust HashMap (hashbrown) 0.875 (7/8)
Go map (Swiss tables, Go 1.24+) 0.875
Zig std.HashMap 80% by default (configurable)
Python dict ~0.66

Separate chaining

With separate chaining, each bucket holds a list of all entries that hashed there. Lookup hashes to a bucket, then scans that bucket's list comparing keys.

buckets 0 1 2 3 4 5 "cat" → 3 "dog" → 9 "owl" → 4 "emu" → 1 collision: hash("dog") ≡ hash("owl") mod 6
Separate chaining. Bucket 2 holds two colliding entries in a chain. Java converts a long chain into a red-black tree.

Chaining is simple, tolerates high load factors, and gives stable references: an entry never moves when others are inserted. That stability is why the C++ standard effectively requires chaining for std::unordered_map (its bucket API and reference-stability guarantees). The cost is a pointer chase per entry, which is bad for cache behaviour.

Java's HashMap is chaining with refinements:

  1. The table size is always a power of two, so index = hash & (n - 1) replaces a slow modulo.
  2. Because only the low bits pick the bucket, it first spreads the high bits down: hash = h ^ (h >>> 16).
  3. When one bucket's chain reaches 8 entries (and the table has at least 64 buckets), the chain becomes a red-black tree. Worst-case lookup in a flooded bucket is then O(log n) instead of O(n). It reverts to a list below 6.

Open addressing

With open addressing, all entries live directly in the bucket array. On a collision, you probe other slots in a fixed sequence until you find the key or an empty slot:

  • Linear probing: try i, i+1, i+2, …. It's the most cache-friendly, because probes are adjacent. It suffers from primary clustering: runs of occupied slots grow and merge.
  • Quadratic probing: try i+1, i+4, i+9, … (or triangular numbers). It breaks up clusters.
  • Double hashing: step by a second hash h2(k). It gives the best spread, with less locality.
  • Robin Hood hashing: during insertion, if the new key has probed further than the resident ("is poorer"), swap them and keep inserting the displaced one. This evens out probe lengths and gives low variance.

Deletion is subtle. You can't simply empty a slot, because that would break the probe chain for keys inserted after it, and lookups would stop early and miss them. The options are tombstones (mark the slot deleted, so lookups skip it and inserts reuse it, and rebuild when tombstones pile up) or backward-shift deletion for linear probing (slide later entries back).

// A minimal open-addressing hash map: string keys → int values, linear probing.
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

typedef struct { char *key; int value; } Slot;              // key == NULL: empty
typedef struct { Slot *slots; size_t cap, len; } Map;      // cap is a power of two

static uint64_t fnv1a(const char *s) {
    uint64_t h = 1469598103934665603ULL;
    while (*s) { h ^= (unsigned char)*s++; h *= 1099511628211ULL; }
    return h;
}

static int map_grow(Map *m);

int map_put(Map *m, const char *key, int value) {
    if (m->cap == 0 || (m->len + 1) * 4 > m->cap * 3)       // keep load factor ≤ 0.75
        if (map_grow(m) != 0) return -1;
    size_t i = fnv1a(key) & (m->cap - 1);
    while (m->slots[i].key) {
        if (strcmp(m->slots[i].key, key) == 0) { m->slots[i].value = value; return 0; }
        i = (i + 1) & (m->cap - 1);                           // linear probe, wrap around
    }
    m->slots[i].key = strdup(key);
    m->slots[i].value = value;
    m->len++;
    return 0;
}

int *map_get(const Map *m, const char *key) {
    if (m->cap == 0) return NULL;
    for (size_t i = fnv1a(key) & (m->cap - 1); m->slots[i].key; i = (i + 1) & (m->cap - 1))
        if (strcmp(m->slots[i].key, key) == 0) return &m->slots[i].value;
    return NULL;                                              // hit an empty slot: absent
}

static int map_grow(Map *m) {
    size_t ncap = m->cap ? m->cap * 2 : 16;
    Slot *old = m->slots; size_t ocap = m->cap;
    m->slots = calloc(ncap, sizeof *m->slots);
    if (!m->slots) { m->slots = old; return -1; }
    m->cap = ncap; m->len = 0;
    for (size_t i = 0; i < ocap; i++)                         // rehash everything
        if (old[i].key) { map_put(m, old[i].key, old[i].value); free(old[i].key); }
    free(old);
    return 0;
}

Swiss tables (Google's Abseil flat_hash_map, Rust's hashbrown, Go 1.24+ maps) are the modern state of the art. They split each hash into H1 (which group of 16 slots) and H2 (7 bits stored in a separate control byte array). A lookup loads 16 control bytes into one SIMD register and compares all 16 against H2 in a single instruction. Only slots whose control byte matches are checked against the real key. Probing is effectively group-wise, with high load factors and very few cache misses.

The equality and hash contract

Every language that lets you define your own key types imposes the same contract: equal objects must have equal hashes, and both must be stable while the object is in the table.

public final class Point {
    private final int x, y;
    public Point(int x, int y) { this.x = x; this.y = y; }
    @Override public boolean equals(Object o) {
        return o instanceof Point p && p.x == x && p.y == y;
    }
    @Override public int hashCode() { return 31 * x + y; }   // or Objects.hash(x, y)
}
// Override equals without hashCode → map.get(new Point(1,2)) returns null.
// Mutate a field of a key while it's in a HashMap → the entry becomes unreachable.
// A `record Point(int x, int y)` generates a correct equals/hashCode for you.

Hash sets and iteration order

A hash set is a hash map without values: HashSet<T>, std::unordered_set, Go's map[T]struct{} idiom (zero-byte values), and Zig's std.AutoHashMap(T, void). Iteration order varies by implementation:

  • Java HashMap and Rust HashMap order depends on hashes and capacity, so it can change when the map resizes. Never depend on it.
  • Go randomises iteration order on purpose, so programs can't accidentally depend on it.
  • Python's dict (3.7+), Java's LinkedHashMap and Zig's ArrayHashMap preserve insertion order.
  • Sorted order requires a tree: Java TreeMap, C++ std::map, Rust BTreeMap.

Trees

Tree terminology

A tree is a connected graph with no cycles. A rooted tree picks one node as the root, and every other node has exactly one parent. The vocabulary you'll need:

  • Leaf: a node with no children. Internal node: a node with at least one child.
  • Depth of a node: edges from the root to it. Height of a tree: the maximum depth.
  • Subtree: a node plus all its descendants.
  • Binary tree: at most two children per node, called left and right.
  • Full: every node has 0 or 2 children. Complete: every level full except possibly the last, which is filled from the left (heaps use this shape). Perfect: all leaves at the same depth, with 2^(h+1) − 1 nodes.
  • Balanced: height is O(log n). That's the property all balanced search trees exist to maintain.

Binary trees and traversals

There are four standard ways to visit every node:

Traversal Order Typical use
Pre-order node, left, right Copy or serialise a tree; prefix expressions
In-order left, node, right Sorted order in a BST
Post-order left, right, node Delete or free a tree; evaluate expression trees; compute sizes
Level-order (BFS) level by level, using a queue Shortest depth; printing by level
Text
        8          pre-order:   8 3 1 6 10 14
       / \         in-order:    1 3 6 8 10 14   ← sorted
      3   10       post-order:  1 6 3 14 10 8
     / \    \      level-order: 8 3 10 1 6 14
    1   6    14

Binary search trees

A binary search tree (BST) keeps the invariant: every key in the left subtree < node key < every key in the right subtree. Search, insert and delete all walk one root-to-leaf path, so they're O(h), where h is the height.

  • Search: compare and go left or right.
  • Insert: search until you fall off the tree, and attach the new node there.
  • Delete has three cases. A leaf is simply removed. A node with one child is replaced by that child. A node with two children is replaced by its in-order successor (the leftmost node of the right subtree), and the successor is then deleted from its old spot.
type Node struct {
	Key         int
	Left, Right *Node
}

func Insert(n *Node, k int) *Node {
	if n == nil {
		return &Node{Key: k}
	}
	switch {
	case k < n.Key:
		n.Left = Insert(n.Left, k)
	case k > n.Key:
		n.Right = Insert(n.Right, k)
	}
	return n // duplicates ignored
}

func Contains(n *Node, k int) bool {
	for n != nil {
		if k == n.Key { return true }
		if k < n.Key { n = n.Left } else { n = n.Right }
	}
	return false
}

func InOrder(n *Node, visit func(int)) {
	if n == nil { return }
	InOrder(n.Left, visit); visit(n.Key); InOrder(n.Right, visit)
}

The fatal flaw is that inserting sorted keys (1, 2, 3, 4, …) builds a degenerate tree, effectively a linked list of height n, so every operation becomes O(n). Real systems therefore use self-balancing trees.

Balancing with rotations

Every balanced BST restores balance using rotations: local restructurings that change the shape but keep the in-order sequence, and so keep the BST invariant. A right rotation at y lifts its left child x:

Text
        y                    x
       / \                  / \
      x   C    rotate →    A   y
     / \       right          / \
    A   B                    B   C       in-order stays A x B y C

A rotation is O(1): three pointer changes. The balancing schemes differ in when they rotate.

AVL trees

AVL trees (Adelson-Velsky and Landis, 1962, the first self-balancing BST) store each node's height and enforce |height(left) − height(right)| ≤ 1 at every node. After an insert or delete, walk back up and fix any node whose balance factor reaches ±2 with one of four cases: LL and RR need a single rotation, and LR and RL need a double rotation.

AVL trees are strictly balanced: height ≤ about 1.44 log₂ n. Lookups are slightly faster than in red-black trees, but updates do more rotations. They suit read-heavy workloads.

Red-black trees

A red-black tree colours each node red or black and maintains five rules:

  1. Every node is red or black.
  2. The root is black.
  3. All leaves (the null children, NIL) count as black.
  4. A red node has no red child.
  5. Every path from a node down to its NIL leaves has the same number of black nodes (its black-height).

Rules 4 and 5 together mean the longest path, which alternates red and black, is at most twice the shortest path, which is all black. So height ≤ 2 log₂(n+1). The tree is looser than AVL, but insert needs at most 2 rotations and delete at most 3 (plus recolourings), which makes updates cheaper.

Red-black trees are everywhere: Java TreeMap/TreeSet, Java HashMap tree bins, C++ std::map/std::set (in all major standard libraries), the Linux kernel (CFS scheduler run queue in older kernels, memory regions, epoll), and Nginx timers. You rarely implement one, but you should know the invariants and why they bound the height.

B-trees

Binary trees are a poor fit for both disks and caches. Each node holds one key, so a lookup in a million keys touches about 20 nodes, each a potential cache miss or disk seek. A B-tree packs many keys into each node:

  • A node holds up to m − 1 sorted keys and m child pointers. The fanout m is often 100–1000 for disk pages.
  • Every node except the root is at least half full.
  • All leaves are at the same depth. The tree grows upward: when a node overflows, it splits and pushes its median key up to the parent. When the root splits, the tree gains a level.

With fanout 500, three levels index 500³ = 125 million keys, so a lookup reads three pages. The top one or two levels are almost always cached in memory.

Rust's standard BTreeMap is a B-tree tuned for CPU caches rather than disks: each node holds up to 11 keys (B = 6). Searching inside a node is a linear scan over contiguous keys, which is faster than chasing pointers. It's the default ordered map in Rust, and it typically beats a red-black tree.

B+ trees

A B+ tree is the variant databases and filesystems use. It makes two changes:

  1. Values (or row pointers) live only in the leaves. Internal nodes hold only keys and child pointers, so they fit more keys per page and fanout increases.
  2. Leaves are linked into a sorted list. A range query (WHERE age BETWEEN 20 AND 30) descends once to the first leaf, then walks sideways.
20 | 40 5 · 10 · 15 20 · 25 · 30 40 · 45 · 50 keys < 2020 ≤ keys < 40keys ≥ 40 leaf chain →
A B+ tree with fanout 3. Internal nodes only route; all keys and data are in the leaves, which are chained for range scans.

PostgreSQL's default index, MySQL InnoDB (whose table is a B+ tree clustered on the primary key), SQLite, NTFS, Btrfs and XFS all use B+ trees or close variants. Chapter 58 of the roadmap goes into page layout, fill factors and why random UUIDv4 primary keys cause page splits all over the tree (and why UUIDv7, which is time-ordered, fixes it).

Tries

A trie (prefix tree, from retrieval) stores strings by their characters. Each edge is a character, and a path from the root spells a prefix. Lookup takes O(L) for key length L, independent of how many keys are stored. Tries answer prefix questions directly: "all words starting with pre", autocomplete, and longest-prefix matching.

Text
           (root)
          /   |   \
         c    d    t
         |    |    |
         a    o    o
        / \   |    |\
       t*  r* g*   o* p*      * marks end of a word: cat, car, dog, too, top

A naive trie node has an array of 26 (or 256) child pointers, which is fast but memory-hungry. Real implementations use a hash map of children, sorted small arrays, or compression.

Radix trees

A radix tree (compact prefix tree, or Patricia trie) merges chains of single-child nodes into one edge labelled with a whole substring. romane, romanus and romulus share an edge rom, then split into an and ulus. This shrinks memory dramatically. Uses:

  • IP routing tables: longest-prefix match on address bits.
  • HTTP routers: Go's httprouter and Gin match /users/:id/posts with a radix tree.
  • Linux kernel: the page cache's xarray, a radix tree from file offset to page.
  • Redis: streams and cluster key-slot tracking use its rax radix tree.
  • Ethereum: state is stored in a Merkle-Patricia trie (a radix tree where every node is hashed, see Merkle trees below).

Heaps

The binary heap

A binary heap is a complete binary tree with the heap property: every parent is ≤ its children (a min-heap) or ≥ them (a max-heap). So the minimum (or maximum) is always at the root. Because the tree is complete, it can be stored in a plain array with no pointers at all:

Text
index i:  parent = (i − 1) / 2     left child = 2i + 1     right child = 2i + 2

              1                    array: [1, 3, 2, 7, 4, 5, 9]
            /   \                   index:  0  1  2  3  4  5  6
           3     2
          / \   / \
         7   4 5   9

The heap property is much weaker than BST ordering. Siblings are unordered, so a heap can't search efficiently, but it's exactly enough for "get the minimum fast."

Heap operations

  • push (insert): append at the end, then sift up: swap with the parent while smaller than the parent. O(log n).
  • pop (extract-min): take the root, move the last element to the root, then sift down: swap with the smaller child while larger than it. O(log n).
  • peek: read a[0]. O(1).
  • heapify (build a heap from n unsorted items): sift down every internal node from the last one back to the root. This is O(n), not O(n log n). Most nodes are near the bottom and sift only a short distance, and the sum of heights over all nodes is O(n).
  • decrease-key: needs to know the element's index, so you keep a position map. Dijkstra implementations often skip it and push duplicates instead ("lazy deletion").
// A from-scratch min-heap of ints
type MinHeap []int

func (h *MinHeap) Push(x int) {
	*h = append(*h, x)
	a := *h
	for i := len(a) - 1; i > 0; {
		p := (i - 1) / 2
		if a[p] <= a[i] { break }
		a[p], a[i] = a[i], a[p]
		i = p
	}
}

func (h *MinHeap) Pop() int {
	a := *h
	top := a[0]
	n := len(a) - 1
	a[0] = a[n]
	a = a[:n]
	for i := 0; ; {
		l, r, m := 2*i+1, 2*i+2, i
		if l < n && a[l] < a[m] { m = l }
		if r < n && a[r] < a[m] { m = r }
		if m == i { break }
		a[i], a[m] = a[m], a[i]
		i = m
	}
	*h = a
	return top
}
// Standard library: container/heap works on any type implementing heap.Interface.

The defaults differ between languages (Java min, C++ and Rust max). Check the docs every time.

Heapsort uses a max-heap to sort in place in O(n log n) worst case (chapter 4). Other heap variants: d-ary heaps (4 children per node, shallower and more cache-friendly), pairing and Fibonacci heaps (faster theoretical decrease-key, rarely faster in practice), and indexed heaps.

Graphs

Graph terminology

A graph G = (V, E) is a set of vertices (nodes) and edges connecting pairs of them. Graphs model networks, dependencies, maps, social connections, state machines and build systems. The vocabulary:

  • Directed (edges have a direction: u → v, as in follows on Twitter or package dependencies) versus undirected (u — v, as in friendship or roads).
  • Weighted (edges carry a cost such as distance or latency) versus unweighted.
  • Degree: the number of edges at a vertex. Directed graphs distinguish in-degree and out-degree.
  • Path: a sequence of vertices joined by edges. Cycle: a path that returns to its start.
  • Connected: a path exists between every pair. In directed graphs, strongly connected means a path both ways.
  • DAG (directed acyclic graph): directed with no cycles. DAGs model dependencies: build systems, task schedulers (Airflow), spreadsheets, Git's commit graph, and course prerequisites. Every DAG has a topological order (chapter 4).
  • Sparse (E ≈ V, like road networks) versus dense (E ≈ V², like complete graphs).

Adjacency matrix

An adjacency matrix is a V × V grid where M[u][v] = 1 (or the weight) if an edge u→v exists. An undirected graph has a symmetric matrix.

  • Edge test: O(1). Iterating a vertex's neighbours: O(V), even if it has two.
  • Memory: O(V²). A million vertices would need 10¹² cells, which is impossible.
  • It suits dense graphs, small graphs, and algorithms that are naturally matrix-based (Floyd–Warshall, and graph-theory linear algebra where A^k counts walks of length k).

Adjacency list

An adjacency list stores, for each vertex, a list of its neighbours.

  • Iterating neighbours: O(degree). Edge test: O(degree), or O(1) average if neighbour sets are hash sets.
  • Memory: O(V + E). This is the default for sparse graphs, which most real graphs are.
Text
Graph:  0 → 1, 0 → 2, 1 → 2, 2 → 0, 2 → 3

Adjacency list:            Adjacency matrix:        CSR (compressed sparse row):
0: [1, 2]                      0 1 2 3              offsets: [0, 2, 3, 5, 5]
1: [2]                     0 [ 0 1 1 0 ]            targets: [1, 2, 2, 0, 3]
2: [0, 3]                  1 [ 0 0 1 0 ]            neighbours of v = targets[offsets[v] .. offsets[v+1]]
3: []                      2 [ 1 0 0 1 ]
                           3 [ 0 0 0 0 ]

CSR (compressed sparse row) is the cache-friendly, read-only form: two flat arrays instead of V separate lists. Graph-processing systems and sparse matrix libraries use it.

Rust
// Idiomatic adjacency list: vertices are indices, edges are Vec<usize>
struct Graph { adj: Vec<Vec<usize>> }
impl Graph {
    fn new(n: usize) -> Self { Graph { adj: vec![Vec::new(); n] } }
    fn add_edge(&mut self, u: usize, v: usize) { self.adj[u].push(v); }
}
// Using indices instead of pointers sidesteps ownership problems, halves memory on 64-bit
// (u32 indices), and keeps the structure trivially serialisable.

Choosing a representation

Need Use
Sparse graph, general algorithms (BFS, DFS, Dijkstra) Adjacency list
Dense graph, or frequent "is there an edge u→v?" Adjacency matrix (or a bitset per row)
Huge static graph, analytics CSR
Graph of objects you already have (a DOM, an AST) Implicit: neighbours are fields
Edges with rich data, or edge-centric algorithms (Kruskal) Edge list [(u, v, w), …]
Data that is the product (social, fraud, knowledge graphs) A graph database (chapter 62)

Advanced structures

Union-find (disjoint set union)

Union-find tracks a partition of elements into disjoint sets, with two operations: find(x) returns a representative of x's set, and union(x, y) merges two sets. It answers "are these connected?" as edges arrive, which makes it ideal for Kruskal's MST (chapter 4), detecting cycles in undirected graphs, connected components in image processing, and unification in type inference.

Each set is a tree of parent pointers stored in an array, and the root is the representative. Two optimisations make it extraordinarily fast:

  • Path compression: during find, point every visited node directly at the root.
  • Union by rank or size: attach the shorter or smaller tree under the taller or larger one.

Together they give amortised O(α(n)) per operation, where α is the inverse Ackermann function. α(n) ≤ 4 for any n that could exist in this universe, so it's effectively constant.

struct Dsu { parent: Vec<usize>, size: Vec<usize> }

impl Dsu {
    fn new(n: usize) -> Self { Dsu { parent: (0..n).collect(), size: vec![1; n] } }
    fn find(&mut self, x: usize) -> usize {
        if self.parent[x] != x {
            let root = self.find(self.parent[x]);
            self.parent[x] = root;               // path compression
        }
        self.parent[x]
    }
    fn union(&mut self, a: usize, b: usize) -> bool {
        let (mut ra, mut rb) = (self.find(a), self.find(b));
        if ra == rb { return false; }            // already connected → this edge makes a cycle
        if self.size[ra] < self.size[rb] { std::mem::swap(&mut ra, &mut rb); }
        self.parent[rb] = ra;                    // union by size
        self.size[ra] += self.size[rb];
        true
    }
}

Segment trees

A segment tree answers range queries (sum, min, max, gcd over a[l..r]) and point updates both in O(log n). Each node stores the aggregate of a segment, the root covers the whole array, and children cover halves. Like a heap, it fits in an array of size 2n (iterative bottom-up version) or 4n (recursive version). With lazy propagation, it also supports range updates (add 5 to every element in [l, r]) in O(log n). The combine operation must be associative, which in algebra terms makes it a monoid.

C++
// Iterative (bottom-up) segment tree for range sums. Leaves at [n, 2n).
struct SegTree {
    int n; std::vector<long long> t;
    explicit SegTree(const std::vector<long long>& a) : n(a.size()), t(2 * a.size()) {
        for (int i = 0; i < n; ++i) t[n + i] = a[i];
        for (int i = n - 1; i > 0; --i) t[i] = t[2 * i] + t[2 * i + 1];
    }
    void update(int i, long long v) {            // set a[i] = v
        for (t[i += n] = v; i > 1; i >>= 1) t[i >> 1] = t[i] + t[i ^ 1];
    }
    long long query(int l, int r) {              // sum of a[l, r)
        long long s = 0;
        for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
            if (l & 1) s += t[l++];
            if (r & 1) s += t[--r];
        }
        return s;
    }
};

Fenwick trees

A Fenwick tree (binary indexed tree, BIT) does prefix sums with point updates in O(log n), using exactly n + 1 integers and about ten lines of code. It's simpler and faster than a segment tree when you only need invertible operations like sums, because a range sum is prefix(r) − prefix(l−1).

The trick is in the binary representation. i & -i isolates the lowest set bit (two's complement, chapter 6). Index i stores the sum of the i & -i elements ending at i.

Go
type Fenwick []int64 // 1-indexed; len = n+1

func (f Fenwick) Add(i int, delta int64) {
	for ; i < len(f); i += i & -i { f[i] += delta } // climb to the nodes that cover i
}
func (f Fenwick) Prefix(i int) (s int64) {
	for ; i > 0; i -= i & -i { s += f[i] }           // strip the lowest bit each step
	return
}
// rangeSum(l, r) = f.Prefix(r) - f.Prefix(l-1)

Bloom filters

A Bloom filter answers set membership with a twist: "definitely not in the set" or "probably in the set." It uses a bit array of m bits and k hash functions. To add an item, set the k bits it hashes to. To query, check those k bits: if any bit is 0, the item was never added. If all are 1, it was probably added, unless other items happened to set those bits (a false positive). There are no false negatives. You can't delete in a basic Bloom filter, because clearing a bit might erase other items. Counting Bloom filters and cuckoo filters support deletion.

The false-positive rate after inserting n items is approximately:

Text
p ≈ (1 − e^(−kn/m))^k          optimal k = (m/n) · ln 2
For p = 1%: about 9.6 bits per element and k = 7, regardless of how big the elements are.

That's the payoff. A Bloom filter of 10 million URLs at 1% false positives takes about 12 MB, whatever the URL lengths. It's used to avoid expensive lookups for things that don't exist:

  • LSM-tree databases (RocksDB, Cassandra, HBase, LevelDB) keep one per SSTable, so a read skips files that can't contain the key.
  • CDNs avoid caching "one-hit wonders" (Akamai famously did this).
  • Chrome once used one to check URLs against a malware list locally before asking a server.
  • Spell checkers, distributed joins, and blockchain light clients.
Go
type Bloom struct {
	bits []uint64
	m, k uint64
}

func NewBloom(n int, p float64) *Bloom {
	m := uint64(math.Ceil(-float64(n) * math.Log(p) / (math.Ln2 * math.Ln2)))
	k := uint64(math.Max(1, math.Round(float64(m)/float64(n)*math.Ln2)))
	return &Bloom{bits: make([]uint64, (m+63)/64), m: m, k: k}
}

// Double hashing (Kirsch–Mitzenmacher): k hashes from two, g_i = h1 + i·h2
func (b *Bloom) idx(data []byte) (uint64, uint64) {
	h := fnv.New128a()
	h.Write(data)
	s := h.Sum(nil)
	return binary.LittleEndian.Uint64(s[:8]), binary.LittleEndian.Uint64(s[8:]) | 1
}
func (b *Bloom) Add(data []byte) {
	h1, h2 := b.idx(data)
	for i := uint64(0); i < b.k; i++ {
		j := (h1 + i*h2) % b.m
		b.bits[j/64] |= 1 << (j % 64)
	}
}
func (b *Bloom) MayContain(data []byte) bool {
	h1, h2 := b.idx(data)
	for i := uint64(0); i < b.k; i++ {
		j := (h1 + i*h2) % b.m
		if b.bits[j/64]&(1<<(j%64)) == 0 { return false } // definitely absent
	}
	return true // probably present
}

Skip lists

A skip list is a sorted linked list with "express lanes." Each node is promoted to the next level up with probability ½ (or ¼), so level 1 has about n/2 nodes, level 2 has n/4, and so on. A search starts at the top level, moves right while the next key is smaller, then drops down a level, which gives O(log n) expected search, insert and delete. There are no rotations and no rebalancing, just coin flips.

Text
L3: head ─────────────────────────────▶ 50 ─────────────────▶ nil
L2: head ─────────▶ 20 ───────────────▶ 50 ─────────▶ 80 ───▶ nil
L1: head ─▶ 10 ───▶ 20 ─▶ 30 ─▶ 40 ───▶ 50 ─▶ 60 ───▶ 80 ─▶ 90 ─▶ nil
search 60: L3 → 50 (next is nil, drop) → L2: 80 > 60, drop → L1: 60 ✓

Why choose a skip list over a balanced tree? Mainly concurrency. Inserting changes only local pointers, so lock-free versions are practical. Java's ConcurrentSkipListMap is the JDK's concurrent sorted map. Other users: Redis sorted sets (ZADD/ZRANGE leaderboards, a skip list plus a hash table), and the in-memory memtable of LevelDB and RocksDB.

LSM trees

A log-structured merge tree (LSM tree) is a storage design optimised for write-heavy workloads. B-trees update pages in place with random writes. LSM trees turn every write into sequential I/O:

  1. A write goes to a write-ahead log on disk for durability, and into the memtable, a sorted in-memory structure (a skip list or balanced tree).
  2. When the memtable fills (say 64 MB), it's frozen and flushed to disk as an immutable sorted file called an SSTable (sorted string table), with a sparse index and a Bloom filter.
  3. A read checks the memtable, then SSTables from newest to oldest. Bloom filters skip files that can't hold the key.
  4. In the background, compaction merge-sorts SSTables together. It discards overwritten values and deletions (deletes are written as tombstones), keeping the file count and read cost bounded.
put(k, v) memtable (RAM) WAL (append-only) DISK (immutable sorted files) L0 L0 L1 (10× larger) L2 (10× larger again) flush compactioncompaction get(k): memtable → L0 (newest first) → L1 → L2, skipping files whose Bloom filter says "definitely not"
LSM tree write and read paths. Writes are sequential appends; compaction merges sorted runs in the background.

The trade-offs are captured by three amplification factors. Write amplification is how many times each byte is rewritten by compaction. Read amplification is how many files a read may touch. Space amplification is stale data not yet compacted away. Leveled compaction (RocksDB's default) favours reads and space. Tiered compaction (Cassandra's default STCS) favours writes. LSM trees power RocksDB (which in turn underlies Kafka Streams state stores, CockroachDB via Pebble, and TiKV), LevelDB, Cassandra, ScyllaDB, HBase, Bigtable and InfluxDB.

Merkle trees

A Merkle tree (hash tree) is a binary tree where each leaf holds the hash of a data block and each internal node holds the hash of its children's hashes concatenated. The root hash commits to all the data: change one byte anywhere and the root changes.

Text
                 root = H(H01 ‖ H23)
                /                    \
        H01 = H(H0 ‖ H1)       H23 = H(H2 ‖ H3)
         /         \             /         \
     H0=H(B0)   H1=H(B1)    H2=H(B2)   H3=H(B3)

Two powerful properties follow:

  • Efficient sync: two replicas compare roots. If they differ, they compare children and descend only into subtrees that differ, so finding d differing blocks among n costs O(d log n) hashes exchanged. Cassandra and DynamoDB-style systems use this for anti-entropy repair, and rsync-like tools use similar ideas.
  • Inclusion proofs: to prove block B2 is in the tree, send B2 plus the sibling hashes along its path (H3 and H01). The verifier recomputes the root, which takes O(log n) data. Certificate Transparency logs, Bitcoin's SPV light clients, and Git all rely on this. Git's object model is a Merkle DAG: a commit hashes its tree, which hashes its subtrees and blobs.

ZFS and Btrfs checksum every block in a Merkle-like tree to detect silent disk corruption. IPFS addresses content by Merkle DAG hashes.

Choosing a data structure

Decision guide

Start from the operations you need and how often you'll perform them, then let the constants (cache behaviour, allocation) break ties.

You need… Reach for Avoid
An ordered sequence, append and iterate Dynamic array Linked list
Fast lookup by key, order irrelevant Hash map Sorted array (unless static and read-only)
Keys in sorted order, range queries, floor/ceiling B-tree map (Rust), red-black tree (Java TreeMap, C++ std::map) Hash map + sorting on every query
FIFO processing Ring-buffer deque Array with shifting
Repeatedly take min or max Binary heap Sorting after each insert
Prefix search, autocomplete Trie / radix tree Hash map scan
"Have I seen this?" over huge sets with some error allowed Bloom filter Exact hash set if memory is tight
Connectivity as edges arrive Union-find Repeated BFS
Range sums or min with updates Fenwick tree (sums) / segment tree (any monoid) Recomputing per query
Write-heavy storage engine LSM tree Update-in-place B-tree
Read-heavy, range-heavy storage B+ tree LSM (more read amplification)
Verify or sync large data Merkle tree Hashing everything every time

Measure before you optimise. A sorted Vec with binary search beats a tree for read-mostly data. A linear scan of 50 elements beats a hash map. Hash maps beat everything for random key lookup at scale.

Lab: data structures, measured

Every number in this lab comes from running the code shown (GCC 13 at -O2, JDK 21, Go 1.24, Rust 1.97, CPython 3.13, PostgreSQL 16) on a 2-core cloud sandbox. Absolute times depend on hardware; the ratios are what to remember.

Arrays versus linked lists: the memory hierarchy decides

Big-O says traversing an array and a linked list are both O(n). The hardware disagrees. The same sum over 4 million elements, three layouts:

C
// Same sum, three memory layouts: contiguous array, linked list allocated in order, linked list shuffled
typedef struct Node { long value; struct Node *next; char pad[48]; } Node;   // 64 bytes: one node per cache line
// (array) for (i = 0; i < n; i++) s += arr[i];
// (list)  for (Node *p = head; p; p = p->next) s += p->value;   // nodes linked in address order, then shuffled order
Text
array (8 B per element, contiguous):    4.1 ms  1.02 ns/element
list, nodes in address order:          37.3 ms  9.34 ns/element
list, nodes in shuffled order:        587.9 ms  146.97 ns/element
(sums equal: 1)

A 144× spread for identical O(n) work:

  • The array packs 8 values per 64-byte cache line, and the hardware prefetcher sees the sequential pattern and loads lines before they're needed. Each element costs about a nanosecond.
  • The list in address order touches one 64-byte node per element (8× more memory traffic), but the nodes are still sequential, so prefetching still works.
  • The shuffled list defeats the prefetcher: each p->next is a dependent load from an unpredictable address, so every element waits for a full DRAM round trip (~100+ ns, chapter 7). The CPU can't even start the next load until this one finishes, because it needs the pointer.

This is why "use a linked list for fast insertion" is usually wrong in practice: finding the insertion point already costs a traversal, and a dynamic array's memmove of contiguous memory runs at many GB/s. Linked structures earn their place when you hold pointers to nodes already (LRU caches, intrusive lists in kernels), need stable addresses, or need lock-free algorithms. Java's LinkedList is almost never the right choice; ArrayList and ArrayDeque are.

array: sequential lines, prefetched ahead line 0 line 1 line 2 line 3 line 4 prefetcher runs ahead shuffled list: dependent loads to random addresses node node node node ~100 ns per hop
Why the shuffled list is slow. An array traversal reads consecutive cache lines that the prefetcher fetches ahead of time, so the core rarely waits. A shuffled linked list makes each load depend on the previous one and jump to an unpredictable address, so every step pays the full memory latency.

How dynamic arrays grow, per language

A dynamic array doubles (or grows by some factor) when full, making append amortised O(1): n appends cost O(n) total copying. Each language picks a different factor. Capacities observed while appending 2,000 elements:

Text
Java ArrayList: 10 15 22 33 49 73 109 163 244 366 549 823 1234 1851 2776
Go slice:       1 2 4 8 16 32 64 128 256 512 848 1280 1792 2560
Rust Vec:       4 8 16 32 64 128 256 512 1024 2048
C++ vector:     1 2 4 8 16 32 64 128 256 512 1024 2048
Python list:    4 8 16 24 32 40 52 64 76 92 108 128 148 172 200 232 268 308 352 400 456 520 592 672 760 860 972 1100 1244 1404 1584 1788 2016
  • Java starts at 10 and grows by 1.5× (old + old >> 1).
  • Go doubles up to 256, then grows by roughly 1.25× plus a constant, rounded to allocator size classes (848, 1280…): less wasted memory for big slices.
  • Rust and libstdc++ double (Rust starts at 4 for small element types).
  • Python grows by about 1.125× plus a small constant: many more reallocations, less slack.

The trade-off is memory slack vs copying: factor 2 wastes up to 50% of capacity but copies each element at most about twice on average; factor 1.125 wastes ≤ 12.5% but reallocates far more often. A factor below the golden ratio (≈1.618) also lets an allocator eventually reuse the freed blocks for a new allocation, one argument for 1.5. Practical rule in every language: pre-size when you know the count (new ArrayList<>(n), make([]T, 0, n), Vec::with_capacity(n), reserve(n)), which removes every reallocation and the latency spikes that big copies cause.

Hash tables: why load factor matters

Average probes per successful lookup, measured on a 100,003-slot table, against the textbook formulas (Knuth):

Python
# Open addressing (linear probing) vs separate chaining: average probes for successful lookups, by load factor
def linear(m, n):
    table = [None] * m; probes = 0
    keys = random.sample(range(10**9), n)
    for k in keys:
        i = hash(k * 2654435761) % m
        while table[i] is not None: i = (i + 1) % m
        table[i] = k
    for k in keys:
        i = hash(k * 2654435761) % m; p = 1
        while table[i] != k: i = (i + 1) % m; p += 1
        probes += p
    return probes / n
Text
 load α  linear probing   theory ½(1+1/(1−α))  chaining  theory 1+α/2
   0.25            1.17                  1.17      1.12          1.12
   0.50            1.50                  1.50      1.25          1.25
   0.75            2.50                  2.50      1.37          1.38
   0.90            5.82                  5.50      1.45          1.45
   0.95            9.49                 10.50      1.47          1.48

Theory and measurement agree (the small deviations at high load are sampling noise: clusters are very sensitive). Two conclusions:

  1. Linear probing degrades sharply above ~0.75 because collisions form clusters that grow by absorbing neighbours (unsuccessful searches are even worse: about ½(1 + 1/(1−α)²), which is 50 probes at α = 0.9). That's why open-addressing tables resize early (Python's dict at ⅔ full, Swiss tables at ⅞ with SIMD group probing that checks 16 slots per instruction).
  2. Chaining degrades gently in probe count, but each probe follows a pointer to a separately allocated node: the cache-miss lesson above. Open addressing with a low load factor usually wins in real time, which is why modern tables (Rust's hashbrown, Go 1.24's Swiss tables, Abseil's flat_hash_map, Python's dict) use it, while Java's HashMap and C++'s unordered_map keep chaining for API reasons (Volume 17, ch. 194A).

Bloom filters: the formula holds

A Bloom filter answers "definitely not present" or "probably present" in a fixed number of bits per item. With m bits, n items and k hash functions, the false-positive rate is about (1 − e^(−kn/m))^k, minimised at k = (m/n)·ln 2. Measured with 100,000 items:

Python
class Bloom:
    def __init__(self, m, k): self.m, self.k, self.bits = m, k, bytearray((m + 7) // 8)
    def _idx(self, item):
        h = hashlib.blake2b(item.encode(), digest_size=16).digest()
        h1, h2 = int.from_bytes(h[:8], "little"), int.from_bytes(h[8:], "little")
        return [(h1 + i * h2) % self.m for i in range(self.k)]          # Kirsch–Mitzenmacher double hashing
    def add(self, item):
        for i in self._idx(item): self.bits[i >> 3] |= 1 << (i & 7)
    def __contains__(self, item): return all(self.bits[i >> 3] >> (i & 7) & 1 for i in self._idx(item))
Text
 4 bits/item, k= 3: measured FP 14.726%   theory 14.689%   memory     49 KiB for 100,000 items
 8 bits/item, k= 6: measured FP  2.183%   theory  2.158%   memory     98 KiB for 100,000 items
10 bits/item, k= 7: measured FP  0.816%   theory  0.819%   memory    122 KiB for 100,000 items
16 bits/item, k=11: measured FP  0.051%   theory  0.046%   memory    195 KiB for 100,000 items

10 bits per item gives under 1% false positives, regardless of how big the items are. That's why LSM-tree databases (RocksDB, Cassandra, ScyllaDB) keep a Bloom filter per SSTable: a point lookup skips every file whose filter says "not here", avoiding a disk read in about 99% of irrelevant files for 1.25 bytes per key of memory. Two implementation details from the code worth remembering: you don't need k independent hash functions (two hashes combined as h₁ + i·h₂ work as well, per Kirsch and Mitzenmacher), and standard Bloom filters can't delete (counting Bloom filters and cuckoo filters can).

B+ trees in a real database

Why databases use B+ trees, shown on PostgreSQL 16 with the pageinspect extension. Indexes on tables of 1,000, 1 million and 10 million integers:

SQL
CREATE INDEX ON t1k(id); CREATE INDEX ON t1m(id); CREATE INDEX ON t10m(id);
SELECT 't10m', level, pg_size_pretty(pg_relation_size('t10m_id_idx')) FROM bt_metap('t10m_id_idx');  -- and the others
SELECT live_items, avg_item_size, page_size FROM bt_page_stats('t10m_id_idx', 1);                  -- a leaf page
EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM t10m WHERE id = 7654321;
Text
 tbl  | height_above_leaves |  size
------+---------------------+--------
 t1k  |                   1 | 40 kB
 t1m  |                   2 | 21 MB
 t10m |                   2 | 214 MB

 entries_in_one_leaf_page | avg_item_size | page_size
                      367 |            16 |      8192

   ->  Bitmap Index Scan on t10m_id_idx  (actual rows=1 loops=1)
         Buffers: shared hit=1 read=2

Each 8 KB page holds 367 keys in a leaf (16 bytes each: key plus a tuple pointer), and internal pages have similar fan-out. So three levels (root, one internal level, leaves) cover 10 million keys, and would cover about 367³ ≈ 50 million; a fourth level reaches about 18 billion. Finding one key out of 10 million touched 3 index pages (one cached, two read) plus one heap page. Compare a balanced binary tree: log₂(10⁷) ≈ 24 levels, each a separate node, each potentially a cache miss or disk read. High fan-out is the whole point: it turns tree height into a tiny constant, and the root and internal levels stay in memory, so a lookup costs about one disk read. Leaf pages are also linked to their neighbours, so range scans (WHERE id BETWEEN …) read leaves sequentially.

Revision sheet: data structures

Key ideas

  • A data structure is a way of arranging data in memory so that the operations you need are cheap; every structure trades some operations off against others.
  • Arrays store items contiguously: O(1) access by index, cache-friendly scanning, O(n) insertion in the middle. Dynamic arrays (Java ArrayList, Python list, Go slices, Rust Vec) double their capacity when full, giving amortised O(1) append.
  • Linked lists give O(1) insert/remove at a known node but O(n) search and poor cache behaviour; in practice arrays usually win.
  • Stacks (last in, first out) model calls, undo and parsing; queues (first in, first out) model waiting work and BFS; a deque does both ends.
  • Hash tables map keys to buckets with a hash function: O(1) average lookup, insert and delete; O(n) worst case under bad hashing or attack. Needs a good hash, correct equality, and resizing at a load factor (Java HashMap: 0.75).
  • Binary search trees keep keys sorted for O(log n) operations only when balanced (red-black, AVL); B-trees are wide balanced trees designed for disks and databases.
  • Heaps give the minimum (or maximum) in O(1) and insert/remove in O(log n): the structure behind priority queues and scheduling.
  • Graphs are vertices plus edges, stored as adjacency lists (sparse) or matrices (dense).
  • Advanced: tries for prefixes, union-find for connectivity, Bloom filters for "definitely not / maybe" membership, skip lists, segment trees.
  • Choose by asking: which operations, how often, how big, ordered or not, concurrent or not, memory budget.

Numbers to remember

Structure Access Search Insert Delete
Array (by index) O(1) O(n) O(n) (append amortised O(1)) O(n)
Sorted array O(1) O(log n) O(n) O(n)
Linked list O(n) O(n) O(1) at a known node O(1) at a known node
Hash table — O(1) average O(1) average O(1) average
Balanced BST — O(log n) O(log n) O(log n)
Binary heap min O(1) O(n) O(log n) O(log n) (min)
  • A Java object header is 8–16 bytes depending on JVM version and settings; a boxed Integer in a collection costs about 16 bytes plus a 4–8 byte reference, which is why int[] can be several times smaller than List<Integer>.

Pitfalls

  • Choosing a linked list for "fast inserts" and then searching it every time.
  • Mutating an object used as a hash key so its hash changes: the entry becomes unreachable.
  • Overriding equals without hashCode in Java (or __eq__ without __hash__ in Python).
  • Assuming hash map iteration order (Go deliberately randomises it).
  • Forgetting the worst case: an unbalanced BST built from sorted input is a linked list.

Glossary

  • Amortised cost: average cost per operation over a long sequence, even if a few are expensive.
  • Load factor: entries ÷ buckets in a hash table.
  • Collision: two keys landing in the same bucket; resolved by chaining or open addressing.
  • Balanced tree: one whose height stays O(log n).
  • Locality: placing data used together close together in memory.
  • Persistent structure: one where updates create new versions and old versions stay valid.