Data structures

21 structures the building blocks are built on. Each page shows what it costs, how it works with a small worked example, and which blocks and problems use it.

How to use this

Read a structure when a building block says it is built on one. In the interview, name the structure and its cost in one sentence (three page reads, O(1) eviction, 12 KB per counter) rather than describing it in full.

Trees, logs and ordered structures

How databases keep data sorted and durable.

B-tree

A balanced search tree whose nodes are whole disk pages holding hundreds of sorted keys each. It exists because disks and SSDs are read in pages, so a tree three or four levels deep can find any one of a billion keys in three or four page reads.

Costs

Point lookup: O(log_B n) ≈ 3–4 page reads · Range scan: O(log_B n + k) · Insert / update: O(log_B n) · Delete: O(log_B n)

LSM tree

A log-structured merge tree buffers writes in a sorted in-memory table and flushes it to disk as immutable sorted files, which background jobs merge into larger files over time. It exists because appending sorted runs is sequential I/O, so a disk or SSD can absorb tens of thousands of random-key writes per second that would otherwise be random page writes.

Costs

Insert / update / delete: O(log m) memory + 1 sequential WAL append · Point lookup: O(levels) file probes, ~1 real read · Range scan: O(levels × log n + k) · Flush memtable: O(m) sequential write · Compaction: ~10× total bytes rewritten over a key’s life (levelled)

Write-ahead log

An append-only file that records every change before the change is applied to the data structures it describes. It exists because a crash can happen between modifying several pages, and replaying a sequential log is the cheapest way to make a set of writes atomic and durable.

Costs

Append a record: O(1), sequential write · Commit: 1 fsync, 0.1–2 ms · Crash recovery: O(log since last checkpoint) · Ship to a replica: O(bytes), sequential read · Truncate: O(1)

Skip list

A sorted linked list with extra layers of "express lane" pointers, so a search skips over many elements at a time and runs in O(log n). It exists because it gives balanced-tree performance with a far simpler implementation, no rebalancing, and natural support for ranges, which is why Redis sorted sets and LSM memtables use it.

Costs

Lookup by key / score: O(log n) expected · Insert: O(log n) expected · Delete: O(log n) expected · Range by rank or score: O(log n + k)

Heap / priority queue

A complete binary tree stored in a flat array where every parent is smaller (min-heap) or larger (max-heap) than its children, so the extreme element is always at index 0. It exists because many systems need to repeatedly take the next most urgent, earliest or best item from a changing set, and a heap does that in O(log n) with no pointers and excellent cache behaviour.

Costs

Peek min / max: O(1) · Insert (push): O(log n) · Pop min / max: O(log n) · Build from n items: O(n) · Top-k of a stream: O(n log k), k memory

Ring buffer

A fixed-size array used as a queue, with a write position that wraps back to the start when it reaches the end so the newest entry overwrites the oldest. It exists because many systems only ever need the most recent N things, and a ring buffer gives that with zero allocation, bounded memory and constant-time operations.

Costs

Append (write): O(1) · Read oldest (dequeue): O(1) · Read last k: O(k) · Snapshot / drain: O(n)

Merkle tree

A tree of hashes where each leaf is the hash of a block of data and each internal node is the hash of its children, so one root hash summarises everything beneath it. It exists so two parties holding large datasets can find exactly where they differ by exchanging a handful of hashes instead of the data.

Costs

Build: O(n) hashes · Compare two trees: O(d × log n) hashes exchanged · Update one block: O(log n) hashes · Prove inclusion: O(log n) hashes

Hashing and probabilistic sketches

Constant-time lookups and counting with tiny memory.

Hash table

An array of slots where a key is stored at the position given by hashing it, so finding a key means computing one hash and reading one slot. It exists because sorted structures cost a logarithm per lookup and most lookups do not need order at all.

Costs

Lookup by key: O(1) average: 1 hash + 1–2 slot reads · Insert: O(1) average: 1 hash + 1 slot write · Delete: O(1) average · Range scan / ordered iteration: Not supported

LRU cache: hash map + doubly linked list

A cache that evicts the entry nobody has touched for the longest time, built from a hash map for O(1) lookup and a doubly linked list that keeps entries in order of last use. It exists because a cache must decide what to throw away when full, and "least recently used" is a cheap, good guess about what will not be needed soon.

Costs

Get: O(1): 1 hash lookup + 4 pointer swaps · Put (new key): O(1): 1 map insert + list push at head · Put (existing key): O(1) · Evict: O(1): unlink the tail

Consistent hash ring

A sorted array of hash positions, each tagged with the node that owns it, arranged as a circle so every key hashes to a point and belongs to the next position clockwise. It exists because hash mod N reassigns almost every key when N changes, and a ring reassigns only the keys between the new position and its predecessor.

Costs

Find owner of key: O(log V): 1 hash + binary search over V positions · Add a node: O(V_node log V) to insert its positions · Remove a node: O(V_node log V) to delete its positions · Rebuild from node list: O(V log V)

Bloom filter

A fixed-size array of bits plus k hash functions: inserting an item sets k bits, and a lookup that finds any of its k bits unset knows the item was never inserted. It exists because "have I seen this key?" over billions of keys would need gigabytes as a set, and the filter answers it in a few bits per item if you accept a small chance of a false "maybe".

Costs

Insert: O(k): k hashes, k bits set · Lookup: O(k): k hashes, k bits read · Delete: Not supported · Union of two filters: O(m): bitwise OR

HyperLogLog

An array of small counters (registers) that each remember the longest run of leading zero bits seen in the hashes routed to them, from which the number of distinct items can be estimated to within about 1%. It exists because counting unique visitors exactly means storing every visitor id, and a HyperLogLog does it in 12 KB no matter how many visitors there are.

Costs

Add item: O(1): 1 hash, 1 register read, 1 max · Count estimate: O(m): harmonic mean over m registers · Merge two HLLs: O(m): element-wise max · Remove item / intersect: Not supported

Count-Min sketch

A small grid of counters with d rows and w columns, where each row has its own hash function; an item increments one counter per row and its frequency estimate is the minimum of those d counters. It exists because keeping an exact count per item over a stream of billions of distinct keys needs a counter for every key, and the sketch needs a fixed few tens of kilobytes while never under-counting.

Costs

Increment item: O(d): d hashes, d counter increments · Estimate frequency: O(d): d hashes, d reads, 1 min · Merge two sketches: O(d·w): element-wise add · Top-k heavy hitters: O(d) per item + O(log k) heap update

Bitmap index

One bit array per distinct value of a column, with bit i set when row i has that value, so a filter is a bitwise AND or OR over arrays instead of a scan over rows. It exists because B-tree indexes on low-cardinality columns such as status or country barely narrow the rows, while a bitmap answers "status = failed AND channel = sms" in a few million CPU-friendly bit operations.

Costs

Filter on one value: O(n/64) word reads · Combine filters (AND / OR / NOT): O(n/64) per operator · Count matches: O(n/64) popcount · Insert / update a row: O(1) per bitmap touched, but

Text, space and time

Structures for prefixes, places, ordering and pipelines.

Trie

A tree where each edge is one character, so the path from the root to a node spells a prefix and every word below that node starts with it. It exists because "all words starting with sys" is one walk of three nodes, not a scan of the dictionary.

Costs

Prefix lookup: O(p) · Top-k completions: O(p + k) · Insert: O(L) · Delete: O(L)

Inverted index

A map from each word to the sorted list of document ids that contain it, the reverse of a document-to-words mapping. It exists because "find every document with these words" becomes intersecting a few short lists instead of reading every document.

Costs

Single-term lookup: O(1) + list length · AND of two terms: O(|A| + |B|) · Ranked top-k: O(matches × log k) · Add a document: O(terms in doc) · Delete a document: O(1) mark

Geohash and hierarchical cells (H3, S2)

A way of turning a latitude and longitude into a short string or integer cell id where nearby places share a prefix, so a map becomes a grid of named cells. It exists because "drivers within 2 km" is a two-dimensional question that ordinary indexes cannot answer, but "drivers in these nine cells" is a plain key lookup.

Costs

Encode a point: O(precision) · Neighbours of a cell: O(1) · Points in a cell: O(1) + members · Radius query: O(cells × members) · Change precision: O(1)

Quadtree

A tree that splits a rectangle of the map into four equal quadrants, and splits any quadrant that holds too many points again, so dense areas get small cells and empty areas stay as one big cell. It exists because a fixed grid wastes effort where nothing is and overflows where everything is.

Costs

Insert a point: O(depth) · Range query (rectangle): O(depth + k) · k nearest: O(depth + k log k) · Move a point: O(depth) × 2

Vector clock

A small array with one counter per node, attached to every version of a value, that records how many updates each node had seen when it wrote. It exists because wall clocks drift, so the only reliable way to say "this version came after that one" is to count events rather than read a clock.

Costs

Local write: O(1) · Compare two versions: O(N) · Merge on sync: O(N) · Detect conflict: O(N)

CRDT

A conflict-free replicated data type: a counter, set, map or text document defined so that any two replicas, updated independently, can be merged into the same result no matter the order the updates arrive. It exists so that offline devices and far-apart regions can accept writes without coordination and still converge.

Costs

Local update: O(1) · Merge two replicas: O(state size) · Read the value: O(replicas) for counters · Remove (sets): O(1) + tombstone

DAG of tasks

A directed acyclic graph: tasks as nodes, "must finish before" as arrows, with no path leading back to where it started. It exists because a pipeline with branches (encode four renditions in parallel, then package) cannot be written as a list, and the graph tells the scheduler exactly what may run now.

Costs

Topological order: O(V + E) · Ready set: O(1) per completion · Critical path: O(V + E) · Retry a task: O(subtree) · Cycle check: O(V + E)