Lam NguyenAlgorithms

Databases

Updated November 11, 2026

Topics
  1. Contest Setup
  2. Binary Search
  3. Dynamic Programming
  4. Range Queries
  5. Priority Queues
  6. Stacks
  7. Hashing
  8. Strings
  9. Graphs and Trees
  10. Graph Theory
  11. Network Flow
  12. Combinatorics
  13. Algebra
  14. Data Structure Design
  15. Performance Optimization
  16. Databases
  17. Selected LeetCode Problems

Ideas from competitive programming that show up inside database systems: keeping old versions around (persistence, MVCC, copy-on-write B-trees), laying sparse data out for fast scans (compressed sparse row), answering membership in little memory (filters and sketches), keeping a sorted table in memory (skip lists), summing over rectangles of a grid (quadtrees), deciding what stays in a full cache (eviction), and folding a stream of rows into a few numbers (accumulators and aggregates). The first section is a lecture that puts these pieces inside a whole database engine, from pages to crash recovery, with OntoDB as the example.

C++ template used by every implementation on this page

Each implementation below starts after this header. A snippet that needs a different modulus defines its own MOD in place of this one.

#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using ull = unsigned long long;
using u32 = uint32_t;
using u64 = uint64_t;
using i64 = int64_t;
using i128 = __int128;
using u128 = unsigned __int128;

using vi = vector<int>;
using vii = vector<vector<int>>;
using pii = pair<int, int>;

#define REP(i, n) for (int i = 0; i < (n); i++)
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define FORD(i, a, b) for (int i = (a); i >= (b); i--)
#define RFOR(i, n) for (int i = (n) - 1; i >= 0; i--)

#define all(x) (x).begin(), (x).end()
#define sz(x) (int)((x).size())

#define fi first
#define se second
#define pb push_back

const int INF = 1e9+7;
const int MOD = 1e9+7;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());

A Database Engine, End to End

The sections after this one are pieces. This one is a lecture that puts them inside a whole engine, following one request from the disk up and back down again, and asking at each layer the question that forces the design. The example throughout is OntoDB, a database management system for ontologies that I am building: its data is RDF triples, and its query language is SPARQL.

The companion book, OntoDB: Database Internals and Vector Search, by Example (PDF, 186 pages), develops every step below in full, with figures and a worked ARIES trace. The OntoDB demo runs it in the browser. A paper extends it to semantic search: why a sort order cannot hold similarity, how a class hierarchy becomes a few ranges of integers in the same B+ tree, and how vector indexes answer the rest.

Why data lives in pages

The first instinct is to read exactly the record you need. But storage does not deal in records: a device reads and writes whole blocks, and one random read costs the same whether you wanted 8 bytes or 4,096. So the engine stops fighting the device and adopts its unit. Data lives in fixed-size pages (OntoDB uses 4 KiB), and page \(i\) sits at byte offset \(i \cdot 4096\), so a page id is all you need to find it. Variable-length records go in slotted pages: a directory at the front points at records packed from the back, so a record can move inside its page without changing its address.

One detail in OntoDB is worth stealing: the first 8 bytes of every page are reserved for a pageLSN (the last log record applied to it) from the very first version, long before the log existed. When logging arrived, the file format did not have to change.

Which pages stay in memory

The database is bigger than memory, so a buffer pool keeps some pages in frames and must pick a victim on every miss. That is cache eviction again, with one twist: a single table scan touches every page once, and plain LRU lets it flush the hot index pages. OntoDB uses LRU-K with \(K = 2\): rank pages by the time since their second-most-recent access, so a page touched once has infinite distance and leaves first. It is the same instinct as 2Q’s probation, expressed as a distance.

The buffer pool also answers two questions that decide everything about recovery later:

Fast engines answer steal and no force, and pay for it with a log that can do both. Hold that thought until the last two sections.

Finding a key in three reads

A balanced binary search tree finds one of \(N\) keys in \(\log_2 N\) steps. If each step is a page read, a billion keys cost 30 reads. The fix is to make each node a whole page with fanout \(F\) in the hundreds:

\[\text{height} = \lceil \log_F N \rceil, \qquad \lceil \log_{500} 10^9 \rceil = 4 .\]

That is the B+ tree: internal nodes hold only separator keys (so the fanout is as large as possible), all values live in leaves, and leaves link to their right sibling so a range scan descends once and then walks sideways. A full leaf splits and copies its first key up to the parent; when the root splits, the tree grows one level, so every leaf stays at the same depth. The top levels are tiny and hot, so in practice a lookup costs one or two real disk reads.

One table, three columns: indexing triples

RDF is one table with three columns: subject, predicate, object. Two problems and two tricks:

  1. Strings are long and repeated. A dictionary maps each term to a dense 64-bit id once, so a triple becomes three integers, 24 bytes.
  2. Byte order must be key order. Comparing keys with memcmp needs the most significant byte first: in little-endian, the id 256 (00 01 …) would sort below 1 (01 00 …). Big-endian makes integer order and byte order the same.

A pattern with its bound positions first is then a prefix, and a prefix is one contiguous key range. For subject 5, the range is \([(5,0,0),\,(6,0,0))\). But “which subjects have object Material?” binds only the last position, so no single ordering serves every pattern. OntoDB keeps the same triples in three orders, SPO, POS, and OSP, which makes every combination of bound positions a prefix scan. Extra orderings change the cost of an answer, never the answer. How much? On LUBM(1), about 100,000 triples, SPO alone reads all 1,131 pages of its tree for ?x rdf:type C; with POS that pattern reads 25. The other three orderings cost 80% more space and made no pattern cheaper, so OntoDB keeps three (results).

A query is a join

?s a ub:Student . ?s ub:name ?name is two scans joined on ?s, and a \(k\)-pattern SPARQL query is a \(k\)-way self-join. The engine runs it as a tree of iterators, each with Init and Next, pulling one row at a time, so LIMIT 10 stops the whole tree after ten rows. Which join to use is the real decision:

To choose, the optimizer estimates sizes. The textbook estimate assumes positions are independent, \(\hat{c} = \lvert p\rvert \cdot \lvert o\rvert / \lvert T\rvert\), and RDF breaks that assumption constantly (rdf:type only ever points at classes), so the error compounds up the plan. Running the plan and printing estimated next to actual rows is how you find the bad guess.

Many users at once

Two transactions, each reading and writing, can interleave into a result neither would produce alone. Two-phase locking fixes that: acquire locks, then release them, never acquire after releasing; the order in which transactions finish acquiring is an equivalent serial order. The question that makes it practical: when may a write lock be released? Not before commit. If \(T_1\) releases an exclusive lock early and \(T_2\) reads the value, then \(T_1\) aborts, \(T_2\) has read something that never existed. So exclusive locks are held to the end at every isolation level, and the levels differ only in how long shared locks are held. A B+ tree also needs latches, short page-level mutexes held only during one tree operation, which protect structure rather than data.

Surviving a crash: the log

Back to steal and no force. At the moment of a crash, the disk can hold uncommitted changes (stolen pages) and miss committed ones (not forced). Both are repairable if one rule holds, the write-ahead rule:

  1. A page goes to disk only after the log records describing it are durable.
  2. A commit is acknowledged only after its commit record is durable.

Rule 1 guarantees undo information exists for anything stolen; rule 2 guarantees redo information exists for anything committed. Commits each need an fsync, so a group commit lets every commit that arrives during one flush share the next. And because a crash can tear the last record, every record carries its length and a checksum: OntoDB uses CRC-32C, like PostgreSQL, RocksDB, and InnoDB.

ARIES: repeat history, then undo

ARIES recovers in three passes:

  1. Analysis reads from the last checkpoint and rebuilds which transactions were running (the losers) and which pages were dirty.
  2. Redo replays every logged change, winners and losers alike, skipping a change when the page’s pageLSN shows it already landed. The database is now exactly as it was at the crash.
  3. Undo rolls back the losers, newest first, writing a compensation record for each step.

The surprising part is redoing changes that are about to be undone. It makes undo start from a precise state, and the compensation records make recovery itself crash-safe: if the machine dies mid-undo, the next recovery redoes the compensations and skips straight past what was already undone. One more subtlety: a B+ tree split caused by a transaction that later aborts must not be undone, because other committed inserts may now live in the new page. ARIES logs the split as a nested top action, redone but never undone, and undoes only the logical insert.

A split also raises a quieter problem. It writes three pages (the old leaf, the new leaf, the parent), and if the log reaches the disk with only the first two records, redo faithfully rebuilds a tree whose parent never heard of the new leaf: scans find every key and point lookups miss some. A multi-page change must reach the log whole or not at all. ARIES uses the nested top action again, InnoDB holds every latch until a mini-transaction commits, and PostgreSQL’s B-link trees make a half split legal. OntoDB’s page store logs a full image of each changed page and wraps every tree insert or delete in a page group: the log flushes nothing past the group’s first record until it closes, and the buffer pool will not evict a page the group holds back. Its crash harness kills a real store inside splits and merges for 200 seeds; making the harness that thorough is what found the problem, and a second one: undo deleted a triple from one index, crashed, and the retry trusted that index and skipped the other two.

Try it

The page store’s recovery runs in OntoDB’s tests and crash harness; the shell’s persistent databases, which you can try now, make a simpler choice: the whole database is in memory and only committed state is ever written to the snapshot (no steal), commits append to a log (no force), so recovery is redo-only, one forward pass. Build it and watch a transaction survive a restart:

./build/dev/ontodb mydb
OntoDB> \load data/tiny.owl
OntoDB> INSERT DATA { <http://example.org/materials#Ceramic> <http://www.w3.org/2000/01/rdf-schema#subClassOf> <http://example.org/materials#Material> . }
inserted 1 triple
OntoDB> \log 3
lsn 35 txn 2 term 18 <http://example.org/materials#Ceramic>
lsn 36 txn 2 update insert (18 9 4)
lsn 37 txn 2 commit
OntoDB> \crash

Reopen mydb and Ceramic is there. \checkpoint writes a snapshot by atomic rename and empties the log, and \verify rebuilds the database from its files and compares it with the live one. The book’s last chapter walks through why each of those steps is safe to crash after.

Persistence

A persistent data structure keeps its old versions: every update produces a new version, and every earlier version stays queryable. An ordinary structure overwrites in place, so its past states are lost.

The mechanism is copy-on-write — each update creates new nodes instead of mutating existing ones, so earlier versions stay intact, the same principle as a git commit.

The trick: don’t copy everything

The naive way to keep old versions is to copy the whole structure on every update. That’s \(O(n)\) per update — far too slow.

The real trick is path copying: when you change one element, you only copy the nodes on the path from the root to that element, and reuse everything else. In a balanced tree of height \(O(\log n)\), that’s only \(O(\log n)\) new nodes per update. Each version is just a different root pointing into a mostly-shared tree.

That single idea — share what didn’t change, copy only what did — is the core of every persistent structure below. A binary trie copies the same way; that version is a persistent trie.

Snapshot Array

LeetCode 1146 — Snapshot Array is the simplest example of persistence. You have an array with three operations: set(i, val), snap() (freeze the current state and return an id), and get(i, snap_id) (read an old snapshot).

You don’t need a fancy tree here. Just keep, for each index, a list of (snap_id, value) events. set appends to the list; get binary-searches for the right snapshot. Old snapshots stay valid because you never erase past events.

C++ implementation
class SnapshotArray {
private:
    int time;
    vector<vector<pii>> snapshot;

public:
    SnapshotArray(int n) {
        time = 0;
        snapshot.resize(n);
        REP(i, n) set(i, 0);
    }

    void set(int i, int val) {
        if (!snapshot[i].empty() && snapshot[i].back().fi == time) {
            snapshot[i].back().se = val;
        }
        else snapshot[i].pb({time, val});
    }

    int snap() {
        return time++;
    }

    int get(int i, int snap_id) {
        auto& history = snapshot[i];
        int left = 0, right = history.size();
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (history[mid].fi == snap_id) return history[mid].se;
            if (history[mid].fi < snap_id) left = mid+1;
            else right = mid;
        }
        return history[left-1].se;
    }
};

/**
 * Your SnapshotArray object will be instantiated and called as such:
 * SnapshotArray* obj = new SnapshotArray(length);
 * obj->set(index,val);
 * int param_2 = obj->snap();
 * int param_3 = obj->get(index,snap_id);
 */

Memory is \(O(\text{number of sets})\) and each get is \(O(\log m)\). No cloning, no trees — just a per-index history.

Persistent Segment Tree

Why do we need this? A plain segment tree is great at range queries — the sum, minimum, or count over some range \([l, r]\) — in \(O(\log n)\). But it only ever knows the current array. The moment you update it, the old array is gone.

Sometimes the question isn’t “what is the range sum now,” but “what was the range sum back at version 5?” Think of an array that changes over time where you still need to answer range queries against any past state: an audit query on yesterday’s data, a “k-th smallest in a range” query built from historical prefixes, or simply a problem that lets you branch off old copies. A plain segment tree can’t do this; a persistent segment tree can, because it keeps every version cheaply and lets you run the same \(O(\log n)\) range query against any root you like.

It’s a normal segment tree, but each update path-copies \(O(\log n)\) nodes and returns a new root. Keep a list of roots and every past version stays queryable.

The classic problem is CSES — Range Queries and Copies: update a position, sum over a range, and copy an array. A copy is basically free — it’s just a new root pointing at the same tree.

C++ implementation
const int MAX_N = 2e5+5;

struct PersistentST {
    struct Node {
        ll sum = 0;
        int left = 0, right = 0;
    };

    int N;
    vi A;
    vector<Node> tree;

    PersistentST(int n, vi& a) : N(n), A(a) {
        tree.reserve(MAX_N);
        tree.pb(Node());
    }

    int join(int l, int r) {
        tree.pb({tree[l].sum + tree[r].sum, l, r});
        return tree.size()-1;
    }

    int build(int v, int tl, int tr) {
        if (tl == tr) {
            tree.pb({A[tl], 0, 0});
            return tree.size()-1;
        }
        int tm = tl + (tr - tl) / 2;
        return join(build(tree[v].left, tl, tm), build(tree[v].right, tm+1, tr));
    }

    int update(int v, int tl, int tr, int pos, int val) {
        if (tl == tr) {
            tree.pb({val, 0, 0});
            return tree.size()-1;
        }
        int tm = tl + (tr - tl) / 2;
        int lc = (v == 0) ? 0 : tree[v].left;
        int rc = (v == 0) ? 0 : tree[v].right;
        if (pos <= tm) return join(update(lc, tl, tm, pos, val), rc);
        else return join(lc, update(rc, tm+1, tr, pos, val));
    }

    int copy(int v) {
        tree.pb(tree[v]);
        return tree.size()-1;
    }

    ll query(int v, int tl, int tr, int ql, int qr) {
        if (v == 0 || ql > qr) return 0;
        if (ql == tl && tr == qr) return tree[v].sum;
        int tm = tl + (tr - tl) / 2;
        ll left = query(tree[v].left, tl, tm, ql, min(tm, qr));
        ll right = query(tree[v].right, tm+1, tr, max(tm+1, ql), qr);
        return left + right;
    }
};

void solve() {
    int n, q; cin >> n >> q;
    vi a(n);
    REP(i, n) cin >> a[i];

    PersistentST segtree(n, a);
    vi roots = {segtree.build(0, 0, n-1)};

    REP(i, q) {
        int type, k; cin >> type >> k;
        k--;

        if (type == 1) {
            int pos, val; cin >> pos >> val;
            pos--;
            roots[k] = segtree.update(roots[k], 0, n-1, pos, val);
        } else if (type == 2) {
            int l, r; cin >> l >> r;
            l--, r--;
            cout << segtree.query(roots[k], 0, n-1, l, r) << '\n';
        } else if (type == 3) {
            roots.pb(segtree.copy(roots[k]));
        }
    }
}

int main() {
    // freopen("name.in", "r", stdin);
    // freopen("name.out", "w", stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);
    int tt = 1;
    // cin >> tt;
    while (tt--) solve();
    return 0;
}

The key detail: nodes are never mutated — update and join only ever push new nodes, so old roots keep working forever. That gives \(O(\log n)\) per update and query, and \(O((n + q)\log n)\) total memory.

For a proper walkthrough with pictures, the USACO Guide’s persistence section is the best CP resource, and SecondThread’s video is a great visual intro.

Heads up: persistent segment trees almost never show up on LeetCode. They’re a competitive-programming (Codeforces / CSES) thing. On LeetCode, Snapshot Array is about as far as persistence goes.

Persistent Queue

Persistence isn’t just about trees. SecondThread’s video also walks through the persistent queue — a queue where every push and pop returns a new queue, leaving the old one intact and still usable.

The trick is a classic: represent the queue as two stacks, a front and a back. You push onto back; you pop from front, and when front runs empty you reverse back into it. Stacks are the easiest structure to make persistent — a stack is just an immutable singly linked list, so push/pop are \(O(1)\) and every intermediate list is automatically a version. Build the queue out of two persistent stacks and you get a queue whose whole history stays alive, which is exactly what you need when different versions branch off and each has to keep enqueueing and dequeuing independently.

(Getting worst-case \(O(1)\) per operation under heavy persistent branching needs Okasaki’s real-time queues with lazy evaluation, but the two-stack idea is the intuition.)

The same idea in databases: MVCC and copy-on-write B-trees

Persistence isn’t only a competitive-programming technique; databases rely on it constantly.

When many transactions read and write at once, a database can’t just overwrite a row: a reader might be halfway through a query that expects the old value. So instead of overwriting, the database keeps the old version and writes a new one. Each version is tagged with the transaction that created it, and every reader sees the version that was current when its transaction began.

This is MVCC — Multi-Version Concurrency Control, used by Postgres, MySQL’s InnoDB, and Oracle. If you’ve read Database Internals, this is the “readers don’t block writers, writers don’t block readers” story: everyone gets a consistent snapshot without waiting on locks, because old versions are still lying around to read from.

But MVCC raises a question: how do you organize all those versions on disk so a snapshot stays consistent? One elegant answer is the copy-on-write (CoW) B-tree, used by storage engines like LMDB and WiredTiger. When you modify a page, you don’t overwrite it — you copy that page, apply the change, and then copy every page along the path up to the root, producing a new root. The old root still points at a fully intact old tree; the new root is the new version.

If that sounds familiar, it should: a copy-on-write B-tree is a persistent segment tree scaled up to disk pages. Same path copying, same structural sharing, same “each version is just a different root.” The payoff is atomic, crash-consistent snapshots — a reader following the old root sees a coherent old database even while a writer is busy building the new one, and the switch to the new version is a single pointer swap.

So the recurring lesson holds at every scale:

Never overwrite; keep the old version and point new readers at the new one.

Compressed Sparse Row

Persistence is about keeping versions. Layout is the other half of storage: how the data sits in memory decides how fast it scans.

A sparse matrix is a matrix that is almost all zeros. Storing it as a full 2D grid is wasteful: an \(n \times m\) matrix costs \(nm\) cells even if only a handful are nonzero. So we store only the nonzeros — but we still want to grab “row \(i\)” instantly, not scan the whole thing. Compressed Sparse Row (CSR) is the layout that does exactly that.

Three arrays

Walk the nonzeros row by row, left to right, and record them in three arrays:

The name is the idea: instead of storing a row number for every nonzero, we store just \(n+1\) row pointers — we compress the row information.

A worked example

Take this \(4 \times 4\) matrix:

        col 0   col 1   col 2   col 3
row 0 [   10      0       0      12  ]
row 1 [    0      0      11       0  ]
row 2 [    0     16       0       0  ]
row 3 [    0      0       0      13  ]

Reading the nonzeros row by row — 10, 12 in row 0, 11 in row 1, 16 in row 2, 13 in row 3:

index:      0    1    2    3    4
values  = [ 10   12   11   16   13 ]
col     = [  0    3    2    1    3 ]

row_ptr = [  0    2    3    4    5 ]
row:        0    1    2    3   (end)

Read it back:

Why store it this way

The competitive-programming case: adjacency lists

A graph is a sparse matrix — its adjacency matrix, where \(A_{u,v} \ne 0\) means an edge from \(u\) to \(v\). Row \(u\)’s nonzero columns are exactly the neighbors of \(u\).

For an unweighted graph every nonzero is just \(1\), so you can drop values entirely: col becomes the flat list of neighbors and row_ptr marks where each vertex’s neighbors begin. That two-array CSR is a fast adjacency list — one contiguous block instead of \(n\) separately heap-allocated vector<int>s. Neighbors of a vertex sit next to each other, so a traversal streams through memory instead of chasing pointers; on graph-heavy problems that is often a 2–3x speedup and a big memory saving. (Weighted graph? Keep values for the edge weights.)

Here it is as a reusable container. Two arrays carry the structure: offset is the row pointer (offset[i] marks where row i’s entries begin), and data is the flat, row-grouped payload — a neighbor (that is, a column index) for an unweighted graph, or a {to, weight} for a weighted one. You stage entries with add(row, x) in any order; build() groups them by row in one linear counting-sort pass (count each row’s size, prefix-sum into offset, scatter into data). Reading a row is a plain pointer walk, so for (int v : G[u]) has no indirection.

C++ implementation (in the CP template style)
template <typename T>
struct CSR {
    int n;
    bool built = false;
    vi offset;         // row offsets (row_ptr): after build, n+1 of them; row i = data[offset[i] .. offset[i+1])
    vi row;            // staged row of each entry (freed after build)
    vector<T> data;    // per-entry payload, grouped by row: a neighbor/column id, or {to, weight} when weighted

    CSR(int n = 0) : n(n) {}

    // stage entry x into row i; any order, any number of times
    void add(int i, const T& x) {
        assert(0 <= i && i < n && !built);
        row.pb(i), data.pb(x);
    }

    // group everything by row in one O(n + nnz) counting sort
    void build() {
        assert(!built);
        built = true;
        int m = sz(data);

        offset.assign(n + 1, 0);
        for (int i : row) offset[i + 1]++;          // 1) count entries per row
        FOR(i, 1, n) offset[i] += offset[i - 1];    // 2) prefix sums -> row starts

        vi cur = offset;                            // 3) scatter into each row's slice
        vector<T> tmp(m);
        REP(k, m) tmp[cur[row[k]]++] = data[k];

        swap(data, tmp);
        row.clear(), row.shrink_to_fit();
    }

    struct range {
        T *first, *last;
        T* begin() const { return first; }
        T* end()   const { return last; }
        int size() const { return int(last - first); }
        bool empty() const { return first == last; }
    };

    range operator[](int i) {
        assert(built);
        // data.data() is the base pointer (element 0); + offset[i] reaches row i's start
        return range{data.data() + offset[i], data.data() + offset[i + 1]};
    }
};

// usage: undirected graph on V vertices, E edges
// CSR<int> G(V);
// REP(e, E) { int u, v; cin >> u >> v; G.add(u, v); G.add(v, u); }
// G.build();
// for (int v : G[u]) { /* visit neighbor v */ }

operator[] hands back a range — just the two pointers first and last that bound row u’s slice in data, exposed through begin() and end(). A range-based for desugars to exactly those two calls, and a raw pointer is already a valid iterator (it supports *, ++, and !=), so for (int v : G[u]) simply walks from first up to last, reading each neighbor straight out of data — no iterator class, no copy.

One caveat: a range holds raw pointers into data, so it is valid only while the CSR lives and is not rebuilt — fine for the usual for (auto&& v : G[u]), but do not stash one for later.

Example: multiplying two sparse matrices

This is the use CSR was invented for. LeetCode 311 — Sparse Matrix Multiplication (premium) asks for the product \(C = A B\) of a sparse \(m \times k\) matrix and a sparse \(k \times n\) matrix. The textbook triple loop is \(O(mkn)\) and spends almost all of it adding \(0 \cdot 0\).

But \(C_{ij} = \sum_{t} A_{it} B_{tj}\), and a term contributes only when both \(A_{it}\) and \(B_{tj}\) are nonzero. So store each matrix in CSR — now the per-entry payload is the full nonzero, a {column, value} pair (the values and col from the top, carried together) — and iterate only over nonzeros: for each nonzero \(A_{it} = a\) in row \(i\), and each nonzero \(B_{tj} = b\) in row \(t\) of \(B\), add \(a \cdot b\) to \(C_{ij}\). The work is proportional to the number of nonzero products, not \(mkn\).

C++ implementation (uses the CSR container above)
struct Info { int idx, val; };   // one nonzero: its column (idx) and value

class Solution {
public:
    vii multiply(vii& mat1, vii& mat2) {
        int m = sz(mat1), k = sz(mat1[0]), n = sz(mat2[0]);

        CSR<Info> A(m), B(k);                       // A stored by its rows, B by its rows
        REP(i, m) REP(t, k) if (mat1[i][t]) A.add(i, {t, mat1[i][t]});
        REP(t, k) REP(j, n) if (mat2[t][j]) B.add(t, {j, mat2[t][j]});
        A.build(), B.build();

        vii C(m, vi(n, 0));
        REP(i, m)
            for (auto& [t, a] : A[i])               // nonzeros of row i of A
                for (auto& [j, b] : B[t])           // nonzeros of row t of B
                    C[i][j] += a * b;
        return C;
    }
};

Here the payload T is Info{column, value} — exactly the values and col of the sparse matrix from the start, carried together per nonzero — and the nested loops walk only the nonzeros CSR grouped by row.

A concrete benchmark

The payoff is easy to measure. LeetCode 1971 — Find if Path Exists in Graph is a plain reachability BFS on an undirected graph (up to \(2 \times 10^5\) vertices and edges). Solve it twice and change only the adjacency storage — a vector<vector<int>> versus the CSR container above. The BFS is identical.

C++ — the same BFS over two adjacency storages
// (1) vector-of-vectors adjacency
class Solution {
public:
    bool validPath(int n, vii& edges, int src, int dst) {
        vector<vi> G(n);
        for (auto& e : edges) { G[e[0]].pb(e[1]); G[e[1]].pb(e[0]); }

        queue<int> q; q.push(src);
        vi seen(n, 0); seen[src] = 1;
        while (!q.empty()) {
            int u = q.front(); q.pop();
            if (u == dst) return true;
            for (int v : G[u]) {
                if (seen[v]) continue;
                q.push(v);
                seen[v] = 1;
            }
        }
        return false;
    }
};

// (2) CSR adjacency (the container above) — the BFS below is byte-for-byte the same
class Solution {
public:
    bool validPath(int n, vii& edges, int src, int dst) {
        CSR<int> G(n);
        for (auto& e : edges) { G.add(e[0], e[1]); G.add(e[1], e[0]); }
        G.build();

        queue<int> q; q.push(src);
        vi seen(n, 0); seen[src] = 1;
        while (!q.empty()) {
            int u = q.front(); q.pop();
            if (u == dst) return true;
            for (int v : G[u]) {
                if (seen[v]) continue;
                q.push(v);
                seen[v] = 1;
            }
        }
        return false;
    }
};

Same input, same judge:

adjacency runtime memory
vector<vector<int>> 240 ms 267.8 MB
CSR 42 ms 250.3 MB

That is more than 5x faster (\(240 / 42 \approx 5.7\)) and 17.5 MB less — about 6.5% of the memory — for the exact same traversal. The whole difference is the layout: CSR’s neighbors sit contiguously in one array, so the BFS streams through memory, while the vector-of-vectors chases \(n\) separate heap allocations and eats a cache miss per vertex. (Submission links, LeetCode login may be needed: CSR, vector-of-vectors.)

When to reach for it

Whenever you have many groups of variable size — matrix rows, or a graph’s vertices — that you fill once and then scan repeatedly, don’t allocate one container per group. Flatten everything into contiguous arrays indexed by a per-group pointer, the way CSR packs a matrix’s rows or a graph’s adjacency. One allocation, cache-friendly reads, and the group boundaries live in a single small row_ptr array.

Filters and Sketches

Persistence keeps old versions, and CSR keeps data compact for scans. The next question a storage engine asks is cheaper still: is this key here at all? If the answer lives on disk, asking it costs a read. A filter answers it from memory, using far less space than the set itself, by allowing one kind of mistake.

Start from a hash set, then give up the keys

A hash set answers membership exactly, but it stores every key. Suppose we only store a few bits per key and forget the keys themselves. What can we still promise?

A Bloom filter is the simplest answer. Keep an array of \(m\) bits, all zero, and \(k\) hash functions. To add a key, set the \(k\) bits it hashes to. To look one up, check those \(k\) bits:

So false negatives are impossible and false positives are the price. That asymmetry is exactly what a database wants in front of disk: a “no” skips the read for free, and a wrong “yes” only costs the read we would have done anyway. A log-structured merge tree keeps one Bloom filter per sorted run, so a point lookup opens only the runs whose filter says yes.

How wrong is “probably”?

After \(n\) insertions with \(k\) hashes, a given bit is still \(0\) with probability \(\left(1 - \tfrac{1}{m}\right)^{kn} \approx e^{-kn/m}\). A false positive needs all \(k\) probed bits set:

\[p \approx \left(1 - e^{-kn/m}\right)^{k}.\]

More hashes set more bits per key (bad) but demand more coincidences per lookup (good). The two balance at \(k = \tfrac{m}{n} \ln 2\), where about half the bits are set. At that point roughly \(9.6\) bits per key buys a \(1\%\) false-positive rate, whatever the keys are.

My notebook’s bloomfilter.h uses two fixed hashes, a base-31 polynomial hash and DJB2. Getting to \(k\) hashes does not need \(k\) independent functions: hash.h builds them from two, as \(g_i(x) = h_1(x) + i \cdot h_2(x)\) (Kirsch and Mitzenmacher), without raising the asymptotic false-positive rate.

What a Bloom filter cannot do: delete

Clearing a key’s bits would also clear bits that other keys rely on, and those keys would start returning “definitely absent”. That is a false negative, the one mistake we promised never to make. So the next question: can we keep a filter’s memory footprint and still delete?

Cuckoo filter: store a fingerprint, not bits

A cuckoo filter stores a short fingerprint of each key (8 bits in my notebook) in a hash table with buckets of \(4\) slots. Each key has two candidate buckets, and its fingerprint sits in one of them. Lookup checks two buckets; delete removes one matching fingerprint. Deletion works because each key owns a slot of its own instead of sharing bits.

The interesting part is relocation. When both buckets are full, insertion evicts a resident fingerprint and moves it to its other bucket, which may evict another, and so on: cuckoo hashing. But we stored only the fingerprint, not the key. How does an evicted fingerprint find its other bucket without the key?

The trick is to define the second bucket from the fingerprint alone:

\[i_2 = i_1 \oplus \text{hash}(f).\]

XOR is its own inverse, so from either bucket, the other is \(i \oplus \text{hash}(f)\). Both directions use only \(f\). This is why cuckoofilter.h rounds the table size \(N\) up to a power of two: reducing \(\bmod N\) keeps the low bits, and XOR commutes with keeping low bits, so \(\big((i_1 \oplus h) \bmod N\big) \oplus (h \bmod N) = i_1\) still holds after the reduction.

size_t i1 = hash(x) % N;
size_t i2 = (i1 ^ hash(to_string(f))) % N;

Two details in the notebook version are worth keeping. The kick loop is capped at MAX_NUM_KICKS, because a full enough table can cycle forever. And when the cap is hit, the swaps are undone in reverse, so a failed insert never loses a fingerprint that was already stored.

Deletes come with one rule: only delete keys you inserted. Deleting a key that was never added can remove a different key that shares its fingerprint and bucket.

Counting instead of membership: count-min sketch

The same idea, hashing into a small table and accepting one-sided error, also estimates how often a key appeared. A count-min sketch keeps \(d\) rows of \(w\) counters, each row with its own hash. An insert adds \(1\) to one counter per row. An estimate reads those \(d\) counters and takes the minimum.

Why the minimum? Every counter a key touches holds its true count plus whatever collided into it, and collisions only ever add. So every row overestimates, and the least overestimated row is the best guess. With \(w = \lceil e / \varepsilon \rceil\) and \(d = \lceil \ln(1/\delta) \rceil\), the estimate exceeds the true count by more than \(\varepsilon N\) (out of \(N\) total insertions) with probability at most \(\delta\).

countminsketch.h seeds each row’s hash separately with SplitMix64. Two sketches built with the same seeds can be merged by adding their counter tables cell by cell, which is how sketches from different machines combine into one. With different seeds the cells mean different things, so merge refuses them.

Skip List

Filters answer “is it here?”. A memtable has to answer “what comes next in sorted order?”, and keep answering while writes stream in. A balanced binary search tree does that, at the cost of rotations on every insert. Is there something simpler with the same \(O(\log n)\)?

Start from a sorted linked list

A sorted linked list inserts in \(O(1)\) once you know where, but finding where takes \(O(n)\) because you can only walk one step at a time. Add a second, sparser list on top that contains every other node: now you walk the top lane until the next step would overshoot, drop down, and walk at most one more step. Each extra lane halves the work again, and with \(\log_2 n\) lanes a search is logarithmic.

Keeping “exactly every other node” under inserts and deletes is as hard as balancing a tree. The skip list’s move is to stop insisting on it: when a node is inserted, flip a coin for each level, and promote it while the coin says heads. On average half the nodes reach level \(1\), a quarter reach level \(2\), and so on. No rebalancing ever happens, and search, insert, and delete take \(O(\log n)\) expected time, with about \(2n\) pointers in total.

The part that is easy to get wrong: the left neighbors

Insert walks down from the top level exactly like search. At each level it remembers the last node it stood on before dropping, the node that will sit to the left of the new one at that level:

for (int i = curr_mx_lvl; i >= 0; i--) {
    while (curr->next[i] != nullptr && curr->next[i]->key < key) {
        curr = curr->next[i];
    }
    left[i] = curr;
}

Then the new node is spliced in after left[i] on every level it reached. My first instinct was to splice using only the final curr, and that is wrong above level \(0\): the left neighbor at a high level is usually a different node, further back. A node is one object referenced from many levels, not one copy per level, so every level needs its own left pointer. If the coin flips the new node above the current top level, its left neighbor up there is the head.

Delete uses the same left array, unlinking the target level by level and stopping at the first level where it does not appear. skiplist.h caps the height at \(16\) levels, enough for about \(2^{16}\) keys at full speed.

Where it shows up

That simplicity is why in-memory sorted tables reach for skip lists. LevelDB and RocksDB keep their memtables in one before flushing to sorted runs on disk (the runs that the Bloom filters above guard), and Redis implements sorted sets with one.

Quadtree

A skip list keeps keys in order along a line. A map, a game board, or a table of readings by latitude and longitude has two coordinates, and the question becomes: what is the sum (or count) over this rectangle, while single cells keep changing?

Two first instincts, and why each falls short

The first instinct is the 2D prefix sum. Store \(P[r][c] = \sum_{i \le r,\, j \le c} g[i][j]\), and any rectangle comes out of four lookups by inclusion-exclusion. Queries are \(O(1)\), but changing one cell changes every \(P[r][c]\) below and to the right of it, which is \(O(nm)\) per update.

The second instinct is to reuse a 1D structure: one segment tree per row. An update touches one tree in \(O(\log m)\), but a query has to ask every row it covers, which is \(O(n \log m)\).

Both make one axis cheap and the other expensive. The question that unblocks it: what does “split the range in half” mean when the range is a rectangle?

Split both axes at once

Cut the rectangle at its middle row and its middle column. That gives four children, the quadrants, and a node stores the sum of its rectangle. This is the segment tree’s idea exactly, with four children in place of two:

Grids are rarely \(2^k \times 2^k\), so the halving is uneven. A node that is a single row has \(r_0 = r_1\), so its middle row is \(r_0\) and the two bottom quadrants \([r_0 + 1, r_1]\) are empty. Skipping empty quadrants is the only special case: a single row then splits like a 1D segment tree, and a \(3 \times 5\) grid needs no padding.

Python implementation
class Node:
    def __init__(self, r0, c0, r1, c1):
        self.r0, self.c0, self.r1, self.c1 = r0, c0, r1, c1
        self.sum = 0
        self.children = []

class QuadTree:
    def __init__(self, grid):
        self.g = grid
        self.root = self.build(0, 0, len(grid)-1, len(grid[0])-1)

    def build(self, r0, c0, r1, c1):
        node = Node(r0, c0, r1, c1)
        if r0 == r1 and c0 == c1:
            node.sum = self.g[r0][c0]
            return node
        rm, cm = (r0 + r1) // 2, (c0 + c1) // 2
        for a, b, c, d in [(r0, c0, rm, cm), (r0, cm + 1, rm, c1),
                           (rm + 1, c0, r1, cm), (rm + 1, cm + 1, r1, c1)]:
            if a <= c and b <= d: # skip empty quadrants
                node.children.append(self.build(a, b, c, d))
        node.sum = sum(child.sum for child in node.children)
        return node

    def update(self, r, c, v, node=None):
        if node is None: node = self.root
        if not (node.r0 <= r <= node.r1 and node.c0 <= c <= node.c1): return
        if not node.children:
            node.sum = v
            return
        for child in node.children: self.update(r, c, v, child)
        node.sum = sum(child.sum for child in node.children)

    def query(self, r0, c0, r1, c1, node=None):
        if node is None: node = self.root
        if node.r1 < r0 or r1 < node.r0 or node.c1 < c0 or c1 < node.c0: return 0
        if r0 <= node.r0 and node.r1 <= r1 and c0 <= node.c0 and node.c1 <= c1: return node.sum
        return sum(self.query(r0, c0, r1, c1, child) for child in node.children)

One Python detail: the default argument is resolved with if node is None, not node = node or self.root. The or form works only as long as every Node is truthy. Give Node a __len__ one day, and a leaf with no children becomes falsy, so the recursion silently restarts from the root.

My implementation is QuadTree.py, and test_quadtree.py checks it against a brute-force sum on random grids up to \(9 \times 9\), including single rows, single columns, and sizes that are not powers of two.

The catch: queries are not logarithmic

In 1D, a query range has two ends, so at most two nodes per level are cut partially, which gives \(O(\log n)\). In 2D a rectangle has a perimeter, and every node its boundary passes through is cut partially.

Take an \(n \times n\) grid and the query “one full row”. At depth \(d\) the nodes have side \(n / 2^d\), and the row passes through \(2^d\) of them, each cut partially. Summing over depths,

\[\sum_{d=0}^{\log_2 n} 2^d \approx 2n,\]

so this query costs \(O(n)\), no better than scanning the row. In general a query costs about its perimeter, not \(O(\log n)\). If all you need is rectangle sums with point updates on a dense grid, a 2D Fenwick tree (a Fenwick tree of Fenwick trees) does both in \(O(\log n \log m)\) with less code.

Worked example: LeetCode 308

LeetCode 308 — Range Sum Query 2D - Mutable asks for exactly this: a matrix of at most \(200 \times 200\), and up to \(5000\) calls mixing update(row, col, val) and sumRegion(row1, col1, row2, col2). The rectangle is inclusive on both corners, which is the convention query already uses, so the solution is the tree plus a thin wrapper:

class NumMatrix:

    def __init__(self, matrix: list[list[int]]):
        self.quadtree = QuadTree(matrix)

    def update(self, row: int, col: int, val: int) -> None:
        self.quadtree.update(row, col, val)

    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
        return self.quadtree.query(row1, col1, row2, col2)

On the sample, sumRegion(2, 1, 4, 3) returns \(8\), and after update(3, 2, 2) it returns \(10\).

The constraints are also a good place to see the perimeter cost from the previous section. I counted the nodes query visits on a \(200 \times 200\) grid:

Query Nodes visited
the whole grid \(1\)
one full row, (100, 0, 100, 199) \(909\)
the whole grid minus its border, (1, 1, 198, 198) \(2717\)
worst of \(3000\) random rectangles \(2841\)

The whole grid is one stored sum, but shaving a single cell off each side puts the boundary through every level of the tree, and the cost jumps by three orders of magnitude. An update visits \(33\) nodes. So the worst case is about \(5000 \times 2800 \approx 1.4 \times 10^7\) node visits, small enough to pass in Python, though a 2D Fenwick tree answers each query with four prefix sums of about \(8 \times 8\) steps, roughly \(256\) in all. The full solution is 308.py.

So why a quadtree?

Because the structure above is the dense version, a full tree down to every cell. The quadtree’s real strength is that it does not have to be full. Split a square only while it holds more than a few points (a point-region quadtree), or only while its cells are not all equal (a region quadtree), and the tree’s size follows the data instead of the grid. Empty ocean on a map, or a solid block in an image, is one leaf. A 2D Fenwick tree cannot do that: it allocates every cell up front.

The descent also has a name you have likely seen. Number the quadrants \(0\) to \(3\) and write down the path from the root to a cell: that string is a quadkey. Bing Maps names its map tiles this way, and a geohash is the same idea, interleaving the bits of longitude and latitude. Two cells that share a long prefix are close, which turns a 2D lookup into a prefix search on a 1D key, and a 1D key is something a B-tree or a sorted table already indexes well. MongoDB’s legacy 2d index stores geohashes for this reason.

Worked example: LeetCode 427, where the node forgets its region

LeetCode 427 — Construct Quad Tree builds exactly this sparse kind of tree. Given an \(n \times n\) grid of \(0\)s and \(1\)s, with \(n = 2^x\), return a quadtree in which every leaf is a square of one value, and a square is split only when its cells differ.

The node is not the one from QuadTree.py. It has no coordinates and no list of children, only a value, a leaf flag, and four named children:

class Node:
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        ...

So where did the region go? In LeetCode 308 every node stores its rectangle (r0, c0, r1, c1), because query compares that rectangle against an arbitrary query rectangle long after the tree is built. Here nothing is ever asked by coordinate. The region is needed only while building, so it lives in the scope of the recursive call: build(r0, c0, r1, c1) knows its square from its arguments, hands each quarter to a child call, and returns a node that does not need to remember any of it. Where a child sits relative to its parent is carried by which field holds it.

The guarantee \(n = 2^x\) is what makes four fixed fields enough. Every split of a \(2^k \times 2^k\) square gives four non-empty \(2^{k-1} \times 2^{k-1}\) squares, so the empty-quadrant check from the rectangle sums version disappears, and topLeft through bottomRight are always filled.

Python implementation
class QuadTree:
    def __init__(self, grid: List[List[int]]):
        self.g = grid
        self.root = self.build(0, 0, len(grid) - 1, len(grid[0]) - 1)

    def build(self, r0, c0, r1, c1):
        if r0 == r1 and c0 == c1:
            return Node(self.g[r0][c0] == 1, True, None, None, None, None)

        rm, cm = (r0 + r1) // 2, (c0 + c1) // 2
        tl = self.build(r0, c0, rm, cm)
        tr = self.build(r0, cm + 1, rm, c1)
        bl = self.build(rm + 1, c0, r1, cm)
        br = self.build(rm + 1, cm + 1, r1, c1)

        # merge when 4 identical leaves
        if tl.isLeaf and tr.isLeaf and bl.isLeaf and br.isLeaf and tl.val == tr.val == bl.val == br.val:
            return Node(tl.val, True, None, None, None, None)
        return Node(False, False, tl, tr, bl, br)


class Solution:
    def construct(self, grid: List[List[int]]) -> 'Node':
        return QuadTree(grid).root

The merge rule is the interesting line. Build bottom-up, and collapse a node into one leaf when its four children are leaves holding the same value. Why is it enough to look only at the children? By induction, every child returned is already merged as far as it can go, so a child whose square is all one value is a leaf. A square is all one value exactly when its four quarters are each all one value, and the same one, so the check is complete. The first instinct, checking “is this square uniform?” by scanning it at every node, rescans each cell once per level and costs \(O(n^2 \log n)\); merging bottom-up looks at each cell once, \(O(n^2)\).

The full solution is 427.py.

Cache Eviction

A cache is full the moment it is useful, so the real design question is not what to store, but who leaves when something new arrives. Every policy is a guess about the future from the past. My notebook puts them behind one interface, eviction_cache.h: get counts as an access, and put returns the page it evicted, if any, so policies can be compared on the same trace.

FIFO: the oldest insert leaves

The first guess is the simplest: whatever arrived first has had its chance. fifo.h keeps a queue of arrivals and a hash map for lookups. Note that get does not touch the queue: in FIFO, using a page buys it nothing. That is exactly its weakness, since a page read on every request is evicted on schedule anyway.

LRU: the least recently used leaves

So let use count. LRU evicts the page untouched for longest, betting that recent use predicts the next use. The question is how to make “touch” and “evict the oldest” both \(O(1)\). A hash map finds a page in \(O(1)\), and a doubly linked list ordered by recency moves any node to the front in \(O(1)\) once you hold a pointer to it, so use both: the map stores pointers into the list. lru.h moves a page to the head on every get and put, and evicts from the tail, using sentinel head and tail nodes so eviction never has to special-case an empty end of the list.

LRU has its own blind spot. One long scan, such as a query reading a whole table once, touches every page exactly once, and each of those pages becomes “most recent” in turn. The scan flushes the hot set, even though none of the scanned pages will be read again.

LFU: the least frequently used leaves

Counting uses instead of timing the last one fixes the scan: a page read once cannot outrank a page read a thousand times. The cost is the opposite blind spot: a page that was hot an hour ago keeps its high count and lingers. An \(O(1)\) LFU keeps a list of pages per frequency and a pointer to the smallest non-empty frequency. That design is the next one to write; lfu.h is a stub for now.

2Q: make a page earn its place

2Q (Johnson and Shasha) keeps LRU’s recency and adds a probation period, so that touching a page once is not enough to enter the hot set. It uses three queues, as in lru-2q.h:

A new page enters A1in. If it ages out without anyone caring, its key passes through A1out and is forgotten. If it is requested again while its key is still in A1out, that second request is the evidence 2Q was waiting for, and the page enters Am. A scan now churns through A1in and A1out and never reaches Am, so the hot set survives it. The ghost queue is what makes this cheap: remembering that a page was seen costs one key, not a page.

The same question in agent memory

A database buffer pool makes this choice for disk pages. An agent with a bounded context makes it for facts, tool results, and past turns: what to keep, what to drop, and what to remember only by name, like A1out, so it can be fetched again if it turns out to matter.

Accumulators and Aggregates

A cache keeps as much as memory allows. An aggregate goes to the other extreme: it reads every row once and keeps only a few numbers. SUM, MAX, and AVG all work this way, and so does a small loop that solves a LeetCode problem. Both have the same shape, and seeing it once makes the database version easy to read.

The problem

LeetCode 3105 gives an array nums and asks for the length of the longest subarray that is strictly increasing or strictly decreasing. For [1, 4, 3, 3, 2] the answer is \(2\): [1, 4] goes up, [4, 3] and [3, 2] go down, and the equal pair 3, 3 is neither.

First instinct: check every subarray

There are \(O(n^2)\) subarrays, and checking one takes up to \(O(n)\). Most of that work is wasted. If nums[i] <= nums[i-1], no increasing subarray can contain both \(i-1\) and \(i\), so everything before \(i\) stops mattering for increasing runs. So which facts about the prefix do we actually need?

Fix the right end \(i\). Every increasing subarray that ends at \(i\) is a suffix of the longest one ending at \(i\), so that longest one is the only one worth tracking. Call its length \(\text{run}_i\). It extends the run ending at \(i-1\) exactly when the last step goes up:

\[\text{run}_i = \begin{cases} \text{run}_{i-1} + 1 & \text{if } \text{nums}[i] > \text{nums}[i-1], \\ 1 & \text{otherwise,} \end{cases} \qquad \text{answer} = \max_i \text{run}_i .\]

This is a DP, but \(\text{run}_i\) depends only on \(\text{run}_{i-1}\), so the table shrinks to two integers: the current run, and the best seen so far.

The accumulator

Put those two integers and their update in a struct:

struct Accumulator {
    int best = 1, run = 1;
    void push(bool ok) {
        run = ok ? run + 1 : 1;
        best = max(best, run);
    }
    int get() const { return best; }
};

class Solution {
public:
    int longestMonotonicSubarray(vi& nums) {
        Accumulator inc, dec;
        FOR(i, 1, sz(nums)-1) {
            inc.push(nums[i] > nums[i-1]);
            dec.push(nums[i] < nums[i-1]);
        }
        return max(inc.get(), dec.get());
    }
};

On [1, 4, 3, 3, 2], each step feeds one comparison to each accumulator:

step \(i\) pair inc gets inc.run dec gets dec.run
1 (1, 4) true 2 false 1
2 (4, 3) false 1 true 2
3 (3, 3) false 1 false 1
4 (3, 2) false 1 true 2

Both best values end at \(2\). Three choices in this code are worth noticing:

That makes it \(O(n)\) time and \(O(1)\) extra space. The array never needs to be in memory at all; the solution works on a stream.

This is how a database computes an aggregate

A query engine computes SUM(x) the same way. It does not collect the column first. It keeps a state, calls a step function on each row, and calls a final function at the end. PostgreSQL names these parts directly in CREATE AGGREGATE, and SQLite’s application-defined aggregates implement the same parts as callbacks:

Accumulator PostgreSQL SQLite
int best, run STYPE aggregate context
best = 1, run = 1 INITCOND zeroed context
push(ok) SFUNC xStep
get() FINALFUNC xFinal
(next section) merge COMBINEFUNC none

Why separate the state from the answer at all? AVG shows why. Its state cannot be the running average, because an average of averages is wrong when the parts have different sizes. The state is the pair (sum, count), and only the final function divides. Here the state is (best, run), and get throws run away.

The initial state matters as well. best = 1, run = 1 already counts the first element, which is correct because LeetCode guarantees \(n \ge 1\). On an empty input it would answer \(1\). SQL aggregates handle this case explicitly: over zero rows, MAX returns NULL and COUNT returns \(0\).

Running two accumulators in one loop is also standard. SELECT MIN(x), MAX(x), AVG(x) FROM t scans t once and updates three states per row, as inc and dec share one pass over nums.

The same question in SQL: gaps and islands

Written declaratively, without a loop, this is the classic gaps and islands query. A table has no “previous element”; the window function LAG provides one. Flag each row that starts a new run, and a running sum of those flags gives every run its own id:

WITH flagged AS (
  SELECT i, x,
         CASE WHEN x > LAG(x) OVER (ORDER BY i) THEN 0 ELSE 1 END AS starts_run
  FROM nums
),
islands AS (
  SELECT i, SUM(starts_run) OVER (ORDER BY i) AS run_id
  FROM flagged
)
SELECT MAX(len) FROM (
  SELECT COUNT(*) AS len FROM islands GROUP BY run_id
);

On the first row LAG returns NULL, the comparison is NULL, and the CASE falls to 1, so the first row starts a run as it should. The query returns \(2\) on the example. It computes the same recurrence: starts_run is !ok, and the length of each island is the final run before a reset. The loop kept one integer; the query writes a flag and an id on every row and then groups them. Both are fine, but the loop shows that the state the query needs is constant-size.

Splitting the scan: what a chunk must tell its neighbor

A parallel scan splits the table into chunks, gives each worker one chunk, and merges the partial states. Can we merge two Accumulators?

The first instinct is best = max(left.best, right.best). That misses any run that crosses the seam: in [1, 2 | 3, 4] each half reports \(2\), but the answer is \(4\). The right half also started its run at \(1\) without knowing what came before it.

So the real question is: what does a chunk have to tell its neighbor? A run crosses the seam only if it ends the left chunk and begins the right one, and joining them depends on a single comparison, the left chunk’s last value against the right chunk’s first. So each chunk reports:

struct Run {
    int first, last, len, pre, suf, best;
};
Run leaf(int x) { return {x, x, 1, 1, 1, 1}; }
Run combine(const Run& a, const Run& b) {
    bool ok = a.last < b.first;           // the one comparison at the seam
    Run c;
    c.first = a.first, c.last = b.last, c.len = a.len + b.len;
    c.pre  = (ok && a.pre == a.len) ? a.len + b.pre : a.pre;
    c.suf  = (ok && b.suf == b.len) ? b.len + a.suf : b.suf;
    c.best = max({a.best, b.best, ok ? a.suf + b.pre : 0});
    return c;
}

The prefix extends past the seam only when the left chunk is a single run (a.pre == a.len), and the suffix likewise. This is the node merge from the segment tree for LeetCode 2213, with “same character” replaced by “goes up”. A segment tree is this combine applied in a fixed tree shape.

combine is associative: any bracketing of the chunks gives the same answer. That is what makes a parallel merge correct, and it holds here (I checked it against brute force on random splits and random merge orders). It is not commutative, though: combine(b, a) compares the wrong ends. Chunks have to be merged in their original order. PostgreSQL’s parallel aggregation makes no such promise about row order, and it does not run in parallel when an aggregate call contains ORDER BY.

Gray et al. classify aggregates by their state. Distributive ones like SUM and MAX merge partial answers directly. Algebraic ones like AVG need a fixed-size state larger than the answer. Holistic ones like MEDIAN have no fixed-size state at all. The longest run is algebraic: its answer is one integer, but its mergeable state is six. Each field has a counterpart in the loop. best stays best, run becomes suf, and the previous element the loop reads as nums[i-1] becomes last. Merging adds pre, first, and len, because a chunk can also be extended on its left, which a loop that only appends never has to handle.

What to take from it

  1. Ask what the next element needs from the past. Here it is the run ending at the previous element. When that fits in a few integers, the DP becomes an accumulator, and the array becomes a stream.
  2. Keep the predicate outside the accumulator. A struct that takes a bool handles every “longest run of adjacent pairs that satisfy P” problem.
  3. To parallelize, ask what a chunk must tell its neighbor. Answering that question gives the combine function, and the combine function must be associative.

From the Notebook

Implementations from my competitive programming notebook, tagged with their USACO Guide level where they have one.

Practice

Persistence

Compressed Sparse Row

All take an edge list and need real traversal over the adjacency — topological order, shortest paths, DFS, tree DP — the repeated neighbor iteration where CSR pays off. (Pure connectivity, like “does a path exist,” is cleaner with union-find and doesn’t exercise CSR.)

Skip List

Quadtree

Cache Eviction

Accumulators and Aggregates

Further reading

A Database Engine, End to End

Accumulators and Aggregates

Compressed Sparse Row