A cache, a game server and a settings screen each need a structure that no standard library ships: one that answers a few specific questions fast. Designing it is mostly a matter of choosing which standard pieces to join.
A custom data structure is a class that wraps standard containers so that a chosen set of operations meets a chosen set of costs. The method is the same every time. List the operations the user will call. Write the cost each one must have, such as O(1) for lookups. Then find, for each operation, the standard container that gives that cost, and join the containers into one class that keeps them in step.
No single container does everything. An array gives O(1) access by index and O(1) append, but searching it takes O(n). A hash map finds a key in O(1) on average and has no order you can index. A doubly linked list removes a node in O(1) when you hold the node, but cannot find one. Every structure in this chapter pairs two of these so that the weakness of one is covered by the other.
Need
Composition
Used in
Newest-first order plus lookup by key
hash map to nodes of a linked list
LRU cache
Pick a random item, remove any item
array plus a map from item to index
lucky-draw pool
Minimum or maximum after any pop
stack of pairs, or stack plus heap
min and max stacks
Value as of an earlier time
per-key list sorted by time, binary search
snapshots
Fixed window with a running total
array used as a ring, plus a sum
moving average
Count of uses and recency
map of counts to ordered sets
LFU cache
A harness that replays operations
A structure is tested by calling its methods in some order and checking what comes back. A small helper makes that easy to read and to repeat. It takes a function that builds a fresh object and a list of operations, each a method name and its arguments, calls them in order and returns the results.
ts
exporttype Op = [method: string, ...args: unknown[]]
// Makes an object, calls its methods in order, returns the results.exportfunction replay(make: () => object, ops: Op[]): unknown[] {
const target = make() as any
return ops.map(([name, ...args]) => target[name](...args))
}
The helper treats the object as any because it looks the method up by name, which TypeScript cannot check. That is acceptable in a test tool. The lessons that follow use replay in their demos and tests, so each demo is a list of operations and the results in the same order. Code blocks follow the convention set out in the first chapter.
A first design: a queue without repeats
A job queue should accept each job once while it waits, so a second request for a job already queued is ignored. The operations are enqueue (returns whether the job was new), dequeue and size, and all three should cost O(1).
A queue needs the oldest item out quickly, and a set needs a fast membership test. An array with a moving head index gives the first, since taking an item only moves the index, and a Set gives the second. The class keeps both. The invariant that matters is that the set holds exactly the items that are in the queue. Every operation must keep it true: enqueue adds to both, and dequeue removes from both.
ts
exportclass UniqueQueue<T> {
items: T[] = []
head = 0
inside = new Set<T>()
enqueue(x: T): boolean {
if (this.inside.has(x)) returnfalsethis.inside.add(x)
this.items.push(x)
returntrue
}
dequeue(): T | undefined {
if (this.head === this.items.length) returnundefinedconst x = this.items[this.head++]
this.inside.delete(x)
if (this.head > 1024 && this.head * 2 > this.items.length) {
this.items = this.items.slice(this.head)
this.head = 0
}
return x
}
size(): number {
returnthis.items.length - this.head
}
}
The array only grows at the end, so the head index leaves old entries behind. When more than 1,024 entries are behind the head and they are over half the array, the class copies the live part into a fresh array. The copy costs O(n) but happens after O(n) dequeues, so each dequeue pays O(1) on average.
Running it
The demo replays nine operations: the same item twice, a dequeue, the same item again after it left, and a dequeue on an empty queue.
enqueue a -> true
enqueue b -> true
enqueue a -> false
size -> 2
dequeue -> a
enqueue a -> true
dequeue -> b
dequeue -> a
dequeue -> undefined
Each operation and what it returned
The second enqueue a returns false, and after a leaves, the next enqueue a returns true. The final dequeue returns undefined, the signal for empty. A queue that held an undefined item would need a different signal, which is one reason these classes return undefined only for "nothing there".
The tests cover the helper, a long run of 2 lakh enqueues and 1.5 lakh dequeues that crosses the compaction threshold, and 2,000 random lists of operations checked against an array. After every step the test compares the sizes of the queue and the set, which is the invariant.
ts
import test from'node:test'import assert from'node:assert/strict'import { mulberry32 } from'./rng.ts'import { replay, type Op } from'./harness.ts'import { UniqueQueue } from'./uniqueq.ts'
test('replay returns one result per operation, in order', () => {
const out = replay(
() => new UniqueQueue<number>(),
[['size'], ['dequeue']],
)
assert.deepEqual(out, [0, undefined])
})
test('a long run keeps the set and the queue in step', () => {
const q = new UniqueQueue<number>()
for (let i = 0; i < 200_000; i++) q.enqueue(i)
for (let i = 0; i < 150_000; i++) assert.equal(q.dequeue(), i)
assert.equal(q.size(), 50_000)
assert.equal(q.inside.size, 50_000)
assert.equal(q.items.length < 200_000, true)
})
ts
test('2,000 random operation lists match a plain array', () => {
const rand = mulberry32(41)
for (let t = 0; t < 2000; t++) {
const q = new UniqueQueue<number>()
const model: number[] = []
for (let step = 0; step < 40; step++) {
if (rand() < 0.6) {
const x = Math.floor(rand() * 6)
const fresh = !model.includes(x)
if (fresh) model.push(x)
assert.equal(q.enqueue(x), fresh)
} else assert.equal(q.dequeue(), model.shift())
assert.equal(q.size(), model.length)
assert.equal(q.inside.size, model.length)
}
}
})
text
✔ replay returns one result per operation, in order (1.8643ms)
✔ a long run keeps the set and the queue in step (34.8959ms)
✔ 2,000 random operation lists match a plain array (10.6489ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0
Output of one run; the millisecond figures vary
Why does the unique queue keep both an array and a set?
The array gives the oldest item in O(1) and the set answers "is it already queued?" in O(1). Neither alone does both.
What invariant must every operation of the unique queue keep?
The set holds exactly the items that are in the queue, so enqueue adds to both and dequeue removes from both.
Why does the queue compact its array only now and then?
Copying the live part costs O(n), but it happens after about n dequeues, so the cost per dequeue stays O(1) on average.
Part 2 · A thumbnail cache that evicts the oldest
The problem
An app shows thumbnails and keeps the most recent few in memory, because loading one from disk is slow. When the cache is full and a new thumbnail arrives, it must drop the one that was used longest ago. This is a least recently used (LRU) cache. It has two operations, both O(1): get(key) returns the value or undefined and marks the key as just used, and put(key, value) stores a value, marks it as just used and, if the cache is over capacity, removes the least recently used key.
The cache needs two things at once. A fast lookup by key, which suggests a hash map. And an order by recency, with O(1) moves to the front and O(1) removal from the back, which suggests a doubly linked list. The map's values are the list's nodes, so a lookup lands on the node, and the node can be unlinked and moved without searching.
The map and the list
Each node knows its key, so that when the oldest node is evicted the class can delete the right entry from the map. Two sentinel nodes, one before the newest and one after the oldest, mean that the code never has to test for an empty list or the ends.
The class starts here. The code from get onwards is in the next two blocks.
ts
exportclass LruCache<V> {
capacity: number
map = new Map<string, Node<V>>()
head = new Node<V>('', undefinedas V) // sentinel before the newest
tail = new Node<V>('', undefinedas V) // sentinel after the oldest
constructor(capacity: number) {
if (!Number.isInteger(capacity) || capacity < 1)
thrownew RangeError('capacity')
this.capacity = capacity
this.head.next = this.tail
this.tail.prev = this.head
}
private unlink(n: Node<V>): void {
n.prev!.next = n.next
n.next!.prev = n.prev
}
private addFront(n: Node<V>): void {
n.next = this.head.next
n.prev = this.head
this.head.next!.prev = n
this.head.next = n
}
ts
get(key: string): V | undefined {
const n = this.map.get(key)
if (!n) returnundefinedthis.unlink(n)
this.addFront(n)
return n.value
}
put(key: string, value: V): void {
const old = this.map.get(key)
if (old) {
old.value = value
this.unlink(old)
this.addFront(old)
return
}
if (this.map.size === this.capacity) {
const oldest = this.tail.prev!
this.unlink(oldest)
this.map.delete(oldest.key)
}
const n = new Node(key, value)
this.map.set(key, n)
this.addFront(n)
}
ts
size(): number {
returnthis.map.size
}
keys(): string[] {
const out: string[] = []
for (let n = this.head.next!; n !== this.tail; n = n.next!)
out.push(n.key)
return out
}
}
How the operations work
get looks up the node, unlinks it and adds it at the front. put on an existing key updates the value and moves the node the same way. put on a new key first checks the size: if the cache is full, the node before the tail sentinel is the oldest, so the class unlinks it and deletes its key from the map. Then it creates the node and adds it at the front. Each step is a constant number of pointer writes and map operations.
The constructor refuses a capacity that is not a whole number of at least 1. The class also gives keys(), which walks from the newest to the oldest, so tests and demos can see the order.
The scene replays a cache of capacity 3.
Animated sceneA get refreshes an entry; a full cache drops the oldest0:19
Watch for the cache holding entries oldest first, with a get moving one to the end
Read it as steps
entries sit oldest first, so the oldest is the one a new put evicts
After three puts the order is c, b, a from newest to oldest. The get of a moves it to the front. The put of d finds the cache full and evicts b, the oldest, so c is the next to go.
The shortcut with Map order
A Map iterates in insertion order, and a key that is deleted and set again goes to the end. That is enough to build the same cache with no list. To mark a key as used, delete it and set it again. To evict, take the first key from map.keys() and delete it.
ts
exportclass LruMap<V> {
capacity: number
map = new Map<string, V>()
constructor(capacity: number) {
if (!Number.isInteger(capacity) || capacity < 1)
thrownew RangeError('capacity')
this.capacity = capacity
}
get(key: string): V | undefined {
if (!this.map.has(key)) returnundefinedconst value = this.map.get(key)!
this.map.delete(key)
this.map.set(key, value) // re-set: now the newestreturn value
}
put(key: string, value: V): void {
if (this.map.has(key)) this.map.delete(key)
elseif (this.map.size === this.capacity) {
this.map.delete(this.map.keys().next().value!) // the oldest
}
this.map.set(key, value)
}
size(): number {
returnthis.map.size
}
keys(): string[] {
return [...this.map.keys()].reverse()
}
}
Both classes run the same operations in the demo, and the last line prints whether all their results are equal.
put a 1 -> undefined
put b 2 -> undefined
put c 3 -> undefined
get a -> 1
put d 4 -> undefined
get b -> undefined
put c 30 -> undefined
get c -> 30
put e 5 -> undefined
keys -> ["e","c","d"]
true
Results for the list version, then whether the map version gave the same
The tests check capacity 1, a capacity of 0 or 2.5 or NaN, which must be refused, and that updating a key refreshes it without growing the cache. The main test runs 3,000 random lists of 40 operations on capacities 1 to 4 and compares both classes with a plain array model after every operation, including the order of the keys.
ts
import test from'node:test'import assert from'node:assert/strict'import { mulberry32 } from'./rng.ts'import { LruCache, LruMap } from'./lru.ts'
test('capacity 1 keeps the newest; bad capacities are refused', () => {
for (const make of [
() => new LruCache<number>(1),
() => new LruMap<number>(1),
]) {
const c = make()
c.put('a', 1)
c.put('b', 2)
assert.equal(c.get('a'), undefined)
assert.equal(c.get('b'), 2)
}
for (const bad of [0, -1, 2.5, NaN])
assert.throws(() => new LruCache<number>(bad), RangeError)
assert.throws(() => new LruMap<number>(0), RangeError)
})
ts
test('updating a key refreshes it and does not grow the cache', () => {
const c = new LruCache<number>(2)
c.put('a', 1)
c.put('b', 2)
c.put('a', 10)
c.put('c', 3)
assert.deepEqual(c.keys(), ['c', 'a'])
assert.equal(c.get('a'), 10)
assert.equal(c.size(), 2)
})
ts
test('3,000 random operation lists: both match a plain array', () => {
const rand = mulberry32(51)
for (let t = 0; t < 3000; t++) {
const cap = 1 + Math.floor(rand() * 4)
const lists = new LruCache<number>(cap)
const maps = new LruMap<number>(cap)
const model: [string, number][] = [] // newest firstfor (let step = 0; step < 40; step++) {
const key = 'k' + Math.floor(rand() * 6)
const at = model.findIndex((e) => e[0] === key)
if (rand() < 0.5) {
const want = at < 0 ? undefined : model[at][1]
if (at >= 0) model.unshift(...model.splice(at, 1))
assert.equal(lists.get(key), want)
assert.equal(maps.get(key), want)
} else {
if (at >= 0) model.splice(at, 1)
elseif (model.length === cap) model.pop()
model.unshift([key, step])
lists.put(key, step)
maps.put(key, step)
}
const order = model.map((e) => e[0])
assert.deepEqual(lists.keys(), order)
assert.deepEqual(maps.keys(), order)
}
}
})
text
✔ capacity 1 keeps the newest; bad capacities are refused (1.764ms)
✔ updating a key refreshes it and does not grow the cache (0.7815ms)
✔ 3,000 random operation lists: both match a plain array (184.0012ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0
Output of one run; the millisecond figures vary
What the shortcut costs
The map version is shorter and needs no node class. It leans on one promise, the insertion order that MDN documents for Map. A get costs four map operations (a check, a read, a delete and a set), where the list version does one lookup and a few pointer writes. A list also lets you pull a node out by a handle you saved, which a policy more complex than "oldest first" may need.
The program below runs 10 lakh operations, 60 per cent of them gets, over 5,000 keys on a cache of 1,000, on both classes, three times.
ts
import { LruCache, LruMap } from'./lru.ts'import { mulberry32 } from'./rng.ts'const N = 1_000_000
const rand = mulberry32(3)
const keys = Array.from(
{ length: N },
() => 'k' + Math.floor(rand() * 5000),
)
const isGet = Array.from({ length: N }, () => rand() < 0.6)
function run(c: {
get(k: string): unknown
put(k: string, v: number): void
}) {
const t = performance.now()
for (let i = 0; i < N; i++) {
if (isGet[i]) c.get(keys[i])
else c.put(keys[i], i)
}
return performance.now() - t
}
for (let r = 1; r <= 3; r++) {
const a = run(new LruCache<number>(1000))
const b = run(new LruMap<number>(1000))
console.log(
`run ${r}: list ${a.toFixed(0)} ms, map ${b.toFixed(0)} ms`,
)
}
text
run 1: list 123 ms, map 170 ms
run 2: list 70 ms, map 167 ms
run 3: list 77 ms, map 162 ms
Three runs on this machine; the times vary
In the three runs above the list version took 70 to 123 ms and the map version 162 to 170 ms, so the shortcut was about 1.4 to 2.4 times slower here. Both are O(1) per operation, and for a cache this small, either is fast enough. The numbers are for this machine and this key pattern.
When the oldest node is evicted, the class must delete its entry from the map, and the node is the only place that knows the key.
What does get do besides returning the value?
It marks the key as just used, by unlinking the node and adding it at the front, or in the map version by deleting and setting the key again.
Why does the Map version delete a key before setting it again?
Setting an existing key leaves it where it was in the insertion order. Deleting first puts it at the end, which is the newest position.
Part 3 · A lucky-draw pool with O(1) removal
The problem
A shop runs a lucky draw. Customers join and withdraw at any time, and the shop picks a winner uniformly at random from those still in. Three operations should be O(1): add, remove and pick.
An array gives a uniform pick in O(1): choose an index with Math.floor(rand() * length). Removal from the middle of an array shifts everything after it, which is O(n). A map from item to position gives the removal's search in O(1), but still leaves the shift. The fix is to avoid the shift: overwrite the removed item with the last item and drop the last slot. Order does not matter for a random pool, so nothing is lost.
The class
The map pos records each item's index in items. Adding appends and records the index. Removing finds the index, copies the last item into that slot, updates the last item's recorded index, deletes the removed item's entry and pops the array.
ts
exportclass RandomSet<T> {
items: T[] = []
pos = new Map<T, number>() // item -> its index in items
add(x: T): boolean {
if (this.pos.has(x)) returnfalsethis.pos.set(x, this.items.length)
this.items.push(x)
returntrue
}
remove(x: T): boolean {
const i = this.pos.get(x)
if (i === undefined) returnfalseconst last = this.items[this.items.length - 1]
this.items[i] = last // the last item fills the holethis.pos.set(last, i)
this.pos.delete(x) // if x was the last item, this removes its entrythis.items.pop()
returntrue
}
has(x: T): boolean {
returnthis.pos.has(x)
}
pick(rand: () => number): T | undefined {
if (this.items.length === 0) returnundefinedreturnthis.items[Math.floor(rand() * this.items.length)]
}
size(): number {
returnthis.items.length
}
}
pick takes the random number generator as a parameter, so a test can pass a seeded one. The seeded mulberry32 from the first chapter makes the draws repeatable. The function must return a number from 0 up to but not including 1, as Math.random and mulberry32 do. A generator that returned exactly 1 would index one past the end and pick would give undefined.
The order of two lines
One detail is the classic bug here. When the item being removed is itself the last item, the "fill the hole" step copies it onto itself, and the map update sets its index. The class sets the moved item's index first and deletes the removed item's entry second, so when both are the same item the entry is deleted. The wrong order deletes first and sets second, which brings the removed item back into the map.
ts
exportfunction removeWrongOrder(
items: number[],
pos: Map<number, number>,
x: number,
): void {
const i = pos.get(x)!
const last = items[items.length - 1]
items[i] = last
pos.delete(x)
pos.set(last, i) // when x was the last item this puts it back
items.pop()
}
After removing the last item, the map still has 30
The array is correct, [10, 20], but pos.has(30) is true and points at index 2, beyond the array. The pool would then refuse to add 30 again, because it thinks 30 is present, and a later pick is unaffected, which makes the bug quiet. The test named "removing the last item, the only item and a repeat" catches it by checking that the map is empty after everything is removed.
Fair draws
The demo adds 1 to 5 and draws 1 lakh times with a seeded generator, counting how often each came up, then removes 3 and draws another 1 lakh times. The last line removes 3 again, removes 5, which is the last item of the array at that point, and then adds 5 back.
ts
import { RandomSet } from'./randomset.ts'import { mulberry32 } from'./rng.ts'const pool = new RandomSet<number>()
for (const x of [1, 2, 3, 4, 5]) pool.add(x)
const rand = mulberry32(2026)
function shares(draws: number): void {
const counts = new Map<number, number>()
for (let i = 0; i < draws; i++) {
const x = pool.pick(rand)!
counts.set(x, (counts.get(x) ?? 0) + 1)
}
const expected = draws / pool.size()
const spread = Math.max(
...[...counts.values()].map((n) => Math.abs(n - expected)),
)
console.log(
[...counts]
.sort((p, q) => p[0] - q[0])
.map(([k, n]) => `${k}:${n}`)
.join(' '),
'largest gap from',
expected,
'is',
spread,
)
}
1:200592:200373:199964:200545:19854 largest gap from 20000 is 1461:249632:251224:251025:24813 largest gap from 25000 is 187
false true [ 1, 2, 4 ]
true [ 1, 2, 4, 5 ]
Counts per item, the largest gap from the expected count, then the removals
Each of the five items was drawn about 20,000 times; the largest gap from 20,000 was 146. With 1 lakh draws and chance 1 in 5 for each item, the standard deviation of a count is about 126, so a gap of this size is ordinary. After the removal of 3 the four items share 25,000 each, with a largest gap of 187. The counts are for this seed. Another seed gives other counts of the same size.
The removal of 3 moved 5 into its slot, and the second removal of 3 returned false. Removing 5 then worked from its new position, and adding it back put it at the end.
The tests also cover the empty pool, where pick returns undefined, picks at the two ends of the range, and 2,000 random lists in which, after every step, each item's recorded index equals its real index.
ts
import test from'node:test'import assert from'node:assert/strict'import { mulberry32 } from'./rng.ts'import { RandomSet } from'./randomset.ts'
test('empty set: pick is undefined, remove is false', () => {
const s = new RandomSet<string>()
assert.equal(
s.pick(() => 0.5),
undefined,
)
assert.equal(s.remove('x'), false)
assert.equal(s.size(), 0)
})
test('removing the last item, the only item and a repeat', () => {
const s = new RandomSet<number>()
s.add(1)
s.add(2)
assert.equal(s.remove(2), true)
assert.equal(s.has(2), false)
assert.equal(s.add(2), true)
assert.equal(s.remove(1), true)
assert.equal(s.remove(2), true)
assert.equal(s.remove(2), false)
assert.deepEqual(s.items, [])
assert.equal(s.pos.size, 0)
})
ts
test('pick can return every item, including the first and last', () => {
const s = new RandomSet<number>()
for (const x of [7, 8, 9]) s.add(x)
assert.equal(
s.pick(() => 0),
7,
)
assert.equal(
s.pick(() => 0.9999999),
9,
)
})
test('2,000 random lists keep the map and the array in step', () => {
const rand = mulberry32(61)
for (let t = 0; t < 2000; t++) {
const s = new RandomSet<number>()
const model = new Set<number>()
for (let step = 0; step < 60; step++) {
const x = Math.floor(rand() * 8)
if (rand() < 0.5) {
assert.equal(s.add(x), !model.has(x))
model.add(x)
} else assert.equal(s.remove(x), model.delete(x))
assert.equal(s.size(), model.size)
s.items.forEach((item, i) => assert.equal(s.pos.get(item), i))
}
}
})
text
✔ empty set: pick is undefined, remove is false (1.3431ms)
✔ removing the last item, the only item and a repeat (0.8129ms)
✔ pick can return every item, including the first and last (0.1742ms)
✔ 2,000 random lists keep the map and the array in step (29.7568ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0
Why can remove swap in the last item instead of shifting?
The pool has no order that matters, so any item can fill the hole. Overwriting one slot and dropping the last takes O(1), where a shift takes O(n).
What goes wrong if the removed item's map entry is deleted before the moved item's index is set?
When the removed item is the last item, the set puts it back into the map, so the pool believes it is still present.
After removing one of five items, what share of draws should each remaining item get?
About one in four, 25,000 of 1 lakh. The run shows 24,813 to 25,122.
Part 4 · The lowest price so far
The problem
A shopping app keeps a stack of prices as a customer adds items, and wants to show the lowest price in the basket at any moment. Besides push and pop, it needs min, and all three must be O(1).
Searching the stack for its minimum takes O(n). Keeping one variable for the minimum fails on pop, because after the minimum leaves, the new minimum is somewhere below and the variable no longer knows where. The fix is to store, with each price, the minimum of everything at or below it. That value does not depend on what is above, so it never has to be recomputed when something is popped.
The min stack
Each entry is a pair: the value and the minimum so far. On push, the new minimum is the smaller of the value and the current top's minimum. pop returns the value and discards the pair. min reads the second field of the top pair. An empty stack answers undefined for pop, top and min. A price of NaN is refused, because Math.min with NaN gives NaN and every entry pushed above it would then report NaN as the minimum.
ts
exportclass MinStack {
items: [value: number, minSoFar: number][] = []
push(x: number): void {
if (Number.isNaN(x)) thrownew RangeError('price')
const min = this.items.length === 0 ? x : Math.min(x, this.min()!)
this.items.push([x, min])
}
pop(): number | undefined {
returnthis.items.pop()?.[0]
}
top(): number | undefined {
returnthis.items[this.items.length - 1]?.[0]
}
min(): number | undefined {
returnthis.items[this.items.length - 1]?.[1]
}
}
The demo pushes 40, 25, 60 and 25, then alternates pop and min.
push 40 -> undefined
push 25 -> undefined
push 60 -> undefined
push 25 -> undefined
min -> 25
pop -> 25
min -> 25
pop -> 60
min -> 25
pop -> 25
min -> 40
pop -> 40
min -> undefined
pop -> undefined
The minimum follows the stack down as items are popped
The minimum is 25 while any 25 is in the stack. After the 60 and the second 25 leave, it is still 25, because of the first 25, and when that goes the minimum becomes 40. Duplicate minimums are not a problem: each pair carries its own value, so a duplicate keeps the minimum alive until the last copy is popped.
A stack that can pop its maximum
A harder variant also needs peekMax and popMax: remove the largest item wherever it is in the stack, and if the largest value appears more than once, remove the one nearest the top. A stack of pairs cannot do this, because the maximum can sit in the middle.
The structure needs three parts. The items are kept in a doubly linked list, so that removing any node is O(1) once the node is known. A max-heap finds the largest item, ordered by value and then by push order so that ties go to the newest. And a removed flag on each node lets the two stay in step without searching the heap: an item removed through one side is only marked, and the heap discards it later when it surfaces at the top. This is lazy deletion.
The heap is the class from the two heaps chapter, copied unchanged into heap.ts, with a comparison function that puts the larger value first and, for equal values, the larger push number first.
ts
import { Heap } from'./heap.ts'class Entry {
value: number
id: number // push order, to break ties
removed = false
prev: Entry | null = null
next: Entry | null = null
constructor(value: number, id: number) {
this.value = value
this.id = id
}
}
exportclass MaxStack {
topEntry: Entry | null = null
nextId = 0
count = 0
heap = new Heap<Entry>(
(a, b) => a.value > b.value || (a.value === b.value && a.id > b.id),
)
ts
push(x: number): void {
if (Number.isNaN(x)) thrownew RangeError('price')
const e = new Entry(x, this.nextId++)
e.prev = this.topEntry
if (this.topEntry) this.topEntry.next = e
this.topEntry = e
this.heap.push(e)
this.count++
}
private remove(e: Entry): void {
e.removed = trueif (e.prev) e.prev.next = e.next
if (e.next) e.next.prev = e.prev
elsethis.topEntry = e.prev // e was the topthis.count--
}
pop(): number | undefined {
if (!this.topEntry) returnundefinedconst e = this.topEntry
this.remove(e)
return e.value
}
top(): number | undefined {
returnthis.topEntry?.value
}
ts
private liveMax(): Entry | undefined {
while (this.heap.size > 0 && this.heap.peek()!.removed)
this.heap.pop()
returnthis.heap.peek()
}
peekMax(): number | undefined {
returnthis.liveMax()?.value
}
popMax(): number | undefined {
const e = this.liveMax()
if (!e) returnundefinedthis.heap.pop()
this.remove(e)
return e.value
}
}
Behaviour and cost
pop removes the top node and marks it. popMax takes the live maximum from the heap, removes it from the heap and the list, and marks it. The helper liveMax pops marked entries off the heap until the top is live. Each node enters the heap once and leaves once, so a long run costs O(log n) per operation in total, amortised.
The demo shows popMax taking the top-most of two equal 5s, then continuing.
With 30, 12, 30, 18 pushed, the first popMax returns the 30 that was pushed third, leaving 30, 12, 18, so top is still 18. The second returns the first 30. The third returns 18, then pop returns 12 and the empty stack answers undefined.
The lazy approach has a cost. Entries marked by pop stay in the heap until a max query reaches them. The next demo pushes and pops 1 lakh values without any max query.
ts
const s = new MaxStack()
for (let i = 0; i < 100_000; i++) {
s.push(i)
s.pop()
}
console.log('live', s.count, 'heap entries', s.heap.size)
s.push(1)
console.log(s.peekMax(), 'heap entries', s.heap.size)
text
live 0 heap entries 1000001 heap entries 3
Stale heap entries after 1 lakh pushes and pops
The stack is empty, yet the heap holds 1 lakh entries. One push and a peekMax then drops every stale entry that ranks above the live one. Three entries are left: the live one and two stale ones that rank below it, the value 0 and an earlier push of the value 1. A workload that pops often and asks for the maximum rarely would need a cleanup rule, such as rebuilding the heap when stale entries outnumber live ones.
Tests
The tests cover empty stacks, a NaN price, ties, and 3,000 random lists of 40 operations compared with plain arrays: after each step they check the minimum, the top, the count and the answers of peekMax and popMax, where the model removes the last occurrence of the largest value.
ts
import test from'node:test'import assert from'node:assert/strict'import { mulberry32 } from'./rng.ts'import { MinStack, MaxStack } from'./minstack.ts'
test('empty stacks answer undefined', () => {
const a = new MinStack()
const b = new MaxStack()
for (const s of [a, b]) {
assert.equal(s.pop(), undefined)
assert.equal(s.top(), undefined)
}
assert.equal(a.min(), undefined)
assert.equal(b.peekMax(), undefined)
assert.equal(b.popMax(), undefined)
assert.throws(() => a.push(NaN), RangeError)
assert.throws(() => b.push(NaN), RangeError)
})
test('popMax removes the topmost of equal maximums', () => {
const s = new MaxStack()
for (const x of [4, 9, 2, 9, 1]) s.push(x)
assert.equal(s.popMax(), 9)
assert.deepEqual([s.pop(), s.pop(), s.pop(), s.pop()], [1, 2, 9, 4])
assert.equal(s.pop(), undefined)
})
ts
test('3,000 random lists match plain arrays', () => {
const rand = mulberry32(71)
for (let t = 0; t < 3000; t++) {
const lo = new MinStack()
const hi = new MaxStack()
const model: number[] = []
Why does each min-stack entry store the minimum so far, not just the value?
The minimum of everything at or below an entry never changes while the entry is in the stack, so popping needs no recomputation.
Why is lazy deletion used in the max stack?
A node removed from the list cannot be found and removed from the heap quickly, so it is only marked, and the heap throws it away when it reaches the top.
Which of two equal maximums does popMax remove?
The one pushed later, which is nearer the top of the stack.
Part 5 · A config store with snapshots
The problem
A settings service holds an array of numeric settings. Operators change them over the day and take snapshots, and later someone asks what the value of setting 7 was at snapshot 3. Copying the whole array at every snapshot would cost O(n) time and memory for each, which is too much for a large array and frequent snapshots.
Store only what changed. Each setting keeps a list of [snapshot, value] entries, one for each snapshot number in which it was written. To read a setting at snapshot s, find the last entry whose snapshot number is at most s. That entry is the value that was in force, since it was written at or before s and nothing later was written until after.
The search
The entries of one setting are in increasing order of snapshot number, because writes always happen in the current snapshot and the current snapshot only goes up. That makes a binary search possible. The helper below returns the index of the last entry whose stamp is at most a given number, or -1 if there is none.
ts
// Index of the last entry whose stamp is at most `at`, or -1 if none.exportfunction lastAtOrBefore(
list: [number, unknown][],
at: number,
): number {
let lo = 0let hi = list.length - 1let found = -1while (lo <= hi) {
const mid = (lo + hi) >> 1if (list[mid][0] <= at) {
found = mid
lo = mid + 1
} else hi = mid - 1
}
return found
}
The loop keeps found as the best index so far and narrows the range: if the middle stamp is at most the target, record it and look to the right, else look to the left. The cost is O(log m) for m entries.
The snapshot array
Every setting starts with the entry [0, 0], the value 0 in snapshot 0. set appends an entry for the current snapshot, or overwrites the last one if it already belongs to the current snapshot, so repeated sets between two snapshots keep one entry. snap returns the current number and moves on. get refuses an index outside the array and a snapshot that has not been taken yet, then searches.
ts
exportclass SnapshotArray {
history: [snap: number, value: number][][]
snapId = 0
constructor(length: number) {
if (!Number.isInteger(length) || length < 0)
thrownew RangeError('length')
this.history = Array.from({ length }, () => [[0, 0]])
}
private check(index: number): void {
if (
!Number.isInteger(index) ||
index < 0 ||
index >= this.history.length
)
thrownew RangeError(`index ${index}`)
}
set(index: number, value: number): void {
this.check(index)
const h = this.history[index]
const last = h[h.length - 1]
if (last[0] === this.snapId) last[1] = value
else h.push([this.snapId, value])
}
snap(): number {
returnthis.snapId++
}
ts
get(index: number, snapId: number): number {
this.check(index)
if (
!Number.isInteger(snapId) ||
snapId < 0 ||
snapId >= this.snapId
)
thrownew RangeError(`snapshot ${snapId} was not taken`)
const h = this.history[index]
return h[lastAtOrBefore(h, snapId)][1]
}
}
The demo sets values, takes three snapshots and reads every setting at each.
Values at each snapshot, then the stored entries of settings 0 and 1
Setting 0 was written three times: 10 before snapshot 0, then 11 and 12 between snapshots 0 and 1. The two later writes shared one entry, so its list is [0, 10] and [1, 12]. Setting 1 was never written and still has only its starting entry, so reading it at any snapshot costs a binary search over one element.
The timestamped variant
A second store keeps text values for named keys, written with a time stamp, and answers "what was this key at time t?". It uses the same lists and the same search, but with times where the snapshots were. A set with a time earlier than the key's last write is refused, because the search needs the list sorted, and a set with an equal time replaces the last value. A time that is not a finite number is refused, for the same reason.
ts
exportclass TimeMap {
data = new Map<string, [at: number, value: string][]>()
set(key: string, value: string, at: number): void {
if (!Number.isFinite(at)) thrownew RangeError('time')
const list = this.data.get(key)
if (!list) {
this.data.set(key, [[at, value]])
return
}
const last = list[list.length - 1]
if (at < last[0])
thrownew RangeError('times must not go backwards')
if (at === last[0]) last[1] = value
else list.push([at, value])
}
get(key: string, at: number): string | undefined {
const list = this.data.get(key)
if (!list) returnundefinedconst i = lastAtOrBefore(list, at)
return i < 0 ? undefined : list[i][1]
}
}
ts
const tm = new TimeMap()
tm.set('theme', 'light', 10)
tm.set('theme', 'dark', 20)
tm.set('theme', 'blue', 20)
for (const at of [5, 10, 19, 20, 99])
console.log(at, tm.get('theme', at))
console.log(tm.get('colour', 10))
text
5 undefined
10 light
19 light
20 blue
99 blue
undefined
A query before any write, at a write, between and after, and an unknown key
Time 5 is before the first write, so the answer is undefined. At 10 the answer is light, and it stays light at 19. Two writes at 20 collapsed into one, so blue replaced dark. An unknown key answers undefined.
Tests
The tests cover the search on an empty list and before, on and after its entries, untouched settings, bad indexes and snapshot numbers, a time that goes backwards and an unknown key. Two random tests compare the structures with brute force: the snapshot array against a full copy of the array at each snapshot, over 2,000 lists of 30 operations, and the time map against a linear scan, for 2,000 lists of writes, querying every time from one before the first to one after the last.
test('2,000 random lists match full copies of the array', () => {
const rand = mulberry32(81)
for (let t = 0; t < 2000; t++) {
const n = 1 + Math.floor(rand() * 4)
const a = new SnapshotArray(n)
const now = new Array<number>(n).fill(0)
const copies: number[][] = []
for (let step = 0; step < 30; step++) {
if (rand() < 0.6) {
const i = Math.floor(rand() * n)
const v = Math.floor(rand() * 9)
a.set(i, v)
now[i] = v
} else {
assert.equal(a.snap(), copies.length)
copies.push([...now])
}
}
copies.forEach((copy, s) =>
copy.forEach((v, i) => assert.equal(a.get(i, s), v)),
)
}
})
ts
test('2,000 random time maps match a linear scan', () => {
const rand = mulberry32(82)
for (let t = 0; t < 2000; t++) {
const tm = new TimeMap()
const log: [number, string][] = []
let at = 0for (let step = 0; step < 15; step++) {
at += Math.floor(rand() * 3)
const v = 'v' + step
tm.set('k', v, at)
if (log.length && log[log.length - 1][0] === at) log.pop()
log.push([at, v])
}
for (let q = -1; q <= at + 1; q++) {
const want = log.filter((e) => e[0] <= q).pop()?.[1]
assert.equal(tm.get('k', q), want)
}
}
})
text
✔ binary search: empty, before, on and after the entries (0.7432ms)
✔ snapshots: untouched cells read 0; bad arguments (0.7912ms)
✔ time map: unknown key, early, equal, backwards (0.6195ms)
✔ 2,000 random lists match full copies of the array (16.8317ms)
✔ 2,000 random time maps match a linear scan (19.1295ms)
ℹ tests 5
ℹ pass 5
ℹ fail 0
Output of one run; the millisecond figures vary
Memory is proportional to the number of writes, not to the number of snapshots times the array size. A write costs O(1) and a read costs O(log m).
Each setting's entries are in increasing snapshot order, because writes happen in the current snapshot and snapshot numbers only increase.
What happens to two sets of one setting between the same two snapshots?
The second overwrites the first entry, since both belong to the same snapshot, so only the last value is kept.
Why does the time map refuse a write with an earlier time?
It would break the sorted order that the binary search depends on.
Part 6 · A moving average on a ring buffer
The problem
A payments dashboard shows the average of the last k transaction amounts as each one arrives. The simple way keeps all amounts and sums the last k each time, which costs O(k) per update. Keeping a running sum is cheaper: add the new amount, and subtract the amount that fell out of the window. That needs the amount that fell out, which means remembering the last k amounts, and no more.
A ring buffer, or circular buffer, is a fixed-size array used as if its ends were joined. When the write position reaches the end, it wraps to cell 0 and overwrites the oldest value, which is exactly the one that is leaving the window.
The design
The class keeps the array buf of k cells, start, the index of the oldest value, count, how many cells hold real values, and sum. The cell where the next value goes is (start + count) % k. While the ring is filling, each value goes in at that cell and count grows. Once count equals k, the next value's cell is start itself, the oldest value. The class subtracts it from the sum, overwrites the cell and moves start on by one, wrapping with the remainder.
ts
exportclass MovingAverage {
buf: number[]
start = 0// index of the oldest value
count = 0// how many slots hold real values
sum = 0
constructor(k: number) {
if (!Number.isInteger(k) || k < 1)
thrownew RangeError('window size')
this.buf = new Array<number>(k).fill(0)
}
next(x: number): number {
if (!Number.isFinite(x)) thrownew RangeError(`bad value: ${x}`)
const k = this.buf.length
if (this.count === k) {
this.sum -= this.buf[this.start] // the oldest leavesthis.buf[this.start] = x // its slot is reused by the newestthis.start = (this.start + 1) % k
} else {
this.buf[(this.start + this.count) % k] = x
this.count++
}
this.sum += x
returnthis.sum / this.count
}
}
Why keep count instead of testing a cell for emptiness? A cell may hold a real zero, so zero cannot mean empty. And start equal to the write position is true both when the ring is empty and when it is full. Only count tells the two apart.
Animated sceneThe write pointer wraps and overwrites the oldest value0:25
Watch for the tail passing the last cell and wrapping to cell 0
Read it as steps
a count tells a full ring from an empty one
In the scene, the head is the code's start and the tail is the write position (start + count) % k. The ring in the scene has six cells.
A run past several wraps
The demo uses a window of 3 and amounts in paise. The columns are the amount, the average, start, count and the buffer.
ts
import { MovingAverage } from'./ring.ts'const m = new MovingAverage(3)
for (const paise of [400, 700, 100, 1000, 250, 250, 900]) {
const avg = m.next(paise)
console.log(
String(paise).padStart(5),
'avg',
avg.toFixed(2).padStart(7),
'start',
m.start,
'count',
m.count,
'buf',
m.buf.join(','),
)
}
The fourth amount, 1000, replaces the oldest, 400, in cell 0, and start moves to 1. The average is (700 + 100 + 1000) / 3 = 600. The next two amounts overwrite cells 1 and 2, and the seventh wraps again to cell 0. The ring has wrapped twice by the end, start is back at cell 1, and every average matches the mean of the last three amounts.
A running sum with decimals
A running sum has one risk. Each add and subtract is rounded, and the rounding errors can pile up over a long stream. The demo below feeds 10 lakh values into a window of 3 in three ways and compares the running sum with a sum recomputed from the three cells.
rupees 87.5000000000084687.58.455458555545192e-12
paise 8758750
one outlier 1.7499565056059511.899159676162526 -0.14920317055657506
Running sum, recomputed sum and the difference after 10 lakh values
With amounts in rupees to one decimal, the running sum is 87.50000000000846 where the recomputed sum is 87.5: a small drift, about 8 x 10^-12. With the same amounts in whole paise, the two agree exactly, because integers below 2^53 add and subtract with no rounding. With an occasional huge value, 10^15, entering and leaving the window, the drift is 0.149, since adding a number that large loses the low digits of the small ones, and subtracting it later does not bring them back. The remedy is to keep money in whole paise, and, for general floats, to recompute the sum from the window now and then.
Tests
The tests cover a window of 1, and a window longer than the stream, where the average is over the values seen so far. They check that sizes of 0, -2, 1.5 and NaN and values of NaN or infinity are refused, and that a rejected value leaves count unchanged. A value of 0 is stored and counted. The random test runs 2,000 streams of whole numbers, positive and negative, with windows of 1 to 5, and compares every average with the mean of the last k values recomputed from scratch.
ts
import test from'node:test'import assert from'node:assert/strict'import { mulberry32 } from'./rng.ts'import { MovingAverage } from'./ring.ts'
test('window of 1 and a window larger than the stream', () => {
const one = new MovingAverage(1)
assert.equal(one.next(5), 5)
assert.equal(one.next(9), 9)
const big = new MovingAverage(100)
assert.equal(big.next(4), 4)
assert.equal(big.next(8), 6)
})
test('bad sizes and values are refused', () => {
for (const k of [0, -2, 1.5, NaN])
assert.throws(() => new MovingAverage(k), RangeError)
const m = new MovingAverage(2)
assert.throws(() => m.next(NaN), RangeError)
assert.throws(() => m.next(Infinity), RangeError)
assert.equal(m.count, 0)
})
ts
test('a value of 0 is real: count tells empty from full', () => {
const m = new MovingAverage(2)
assert.equal(m.next(0), 0)
assert.equal(m.count, 1)
assert.equal(m.next(0), 0)
assert.equal(m.count, 2)
assert.equal(m.next(6), 3)
})
test('2,000 random streams match a recomputed mean', () => {
const rand = mulberry32(91)
for (let t = 0; t < 2000; t++) {
const k = 1 + Math.floor(rand() * 5)
const m = new MovingAverage(k)
const seen: number[] = []
for (let i = 0; i < 40; i++) {
const x = Math.floor(rand() * 2000) - 500
seen.push(x)
const window = seen.slice(-k)
const mean = window.reduce((a, b) => a + b, 0) / window.length
assert.equal(m.next(x), mean)
}
}
})
text
✔ window of 1 and a window larger than the stream (0.7711ms)
✔ bad sizes and values are refused (0.5058ms)
✔ a value of 0 is real: count tells empty from full (0.1568ms)
✔ 2,000 random streams match a recomputed mean (13.2544ms)
ℹ tests 4
ℹ pass 4
ℹ fail 0
Output of one run; the millisecond figures vary
Each update is O(1) time. The class holds O(k) cells, whatever the stream length.
How does the class tell a full ring from an empty one?
By count. The write position equals start in both cases, so only the count of stored values tells them apart.
Which value does the sum lose when the ring is full and a new amount arrives?
The value in the cell at start, the oldest one, which is overwritten by the new amount.
Why are amounts held in whole paise?
Whole numbers below 2^53 add and subtract exactly, so the running sum does not drift, as the run shows.
Part 7 · A cache that evicts the least used
The problem
The thumbnail cache of the second lesson evicts by recency. A different cache evicts the entry that has been used the fewest times, which suits data with a few permanently popular items. This is a least frequently used (LFU) cache. Both get and put should be O(1).
There are two questions each time: which entry is used least, and, among entries tied for least, which is the oldest. Counting uses per key is easy with a map. Finding the minimum count in O(1) is the hard part, and so is breaking ties.
The design
Keep a map entries from each key to its value and its use count. Keep a second map byUses from a use count to the set of keys with that count. A Set remembers insertion order, so each set holds its keys with the oldest use first. And keep minUses, the lowest count in the cache.
When a key is used, remove it from the set for its count and add it to the set for the next count, at the end. If the old set is now empty, delete it, and if its count was minUses, then minUses goes up by one, which is right because the key that just left moved to exactly that next count. When a new key arrives, minUses is reset to 1, because the new key has one use.
ts
type Entry<V> = { value: V; uses: number }
exportclass LfuCache<V> {
capacity: number
entries = new Map<string, Entry<V>>()
byUses = new Map<number, Set<string>>() // uses -> keys, oldest first
minUses = 0
constructor(capacity: number) {
if (!Number.isInteger(capacity) || capacity < 1)
thrownew RangeError('capacity')
this.capacity = capacity
}
private touch(key: string, e: Entry<V>): void {
const keys = this.byUses.get(e.uses)!
keys.delete(key)
if (keys.size === 0) {
this.byUses.delete(e.uses)
if (this.minUses === e.uses) this.minUses++
}
e.uses++
if (!this.byUses.has(e.uses)) this.byUses.set(e.uses, new Set())
this.byUses.get(e.uses)!.add(key)
}
ts
get(key: string): V | undefined {
const e = this.entries.get(key)
if (!e) returnundefinedthis.touch(key, e)
return e.value
}
put(key: string, value: V): void {
const e = this.entries.get(key)
if (e) {
e.value = value
this.touch(key, e)
return
}
if (this.entries.size === this.capacity) {
const keys = this.byUses.get(this.minUses)!
const victim = keys.values().next().value!
keys.delete(victim)
if (keys.size === 0) this.byUses.delete(this.minUses)
this.entries.delete(victim)
}
this.entries.set(key, { value, uses: 1 })
if (!this.byUses.has(1)) this.byUses.set(1, new Set())
this.byUses.get(1)!.add(key)
this.minUses = 1
}
ts
size(): number {
returnthis.entries.size
}
}
To evict, the class takes the first key of the set for minUses: the least used and, among those, the one whose latest use is oldest.
A heap ordered by use count and then by last-use time would also find the victim, but each use would cost O(log n) to move the key in the heap. Grouping keys by count turns every move into one set removal and one set insertion, and the minimum is tracked in a number instead of searched for. This is the same trade as the rest of the chapter: spend extra memory on an index so that no operation has to search.
A run with ties
The first demo uses a cache of 3 and the tie block a cache of 2. A get or a put counts as one use of its key. A put of an existing key updates the value and counts as a use.
put a 1 -> undefined
put b 2 -> undefined
put c 3 -> undefined
get a -> 1
get a -> 1
get b -> 2
put d 4 -> undefined
get c -> undefined
put e 5 -> undefined
get d -> undefined
get e -> 5
ties: [ undefined, undefined, undefined, undefined, 2, 3 ]
Results, then a tie where the oldest of two equal keys leaves
The cache holds 3. After the three puts and three gets, a has 3 uses, b has 2 and c has 1. When put d arrives the cache is full, so c, the least used, leaves and get c is undefined. Now d has 1 use and is the least used, so when put e arrives d leaves, and get d is undefined while get e succeeds. In the tie block, a and b each have one use when c arrives, and a is older, so a leaves, and later get b and get c succeed.
Tests
The tests cover the tie rule, a capacity of 1, an update counting as a use and a bad capacity. The random test compares the cache with a model that stores a value, a use count and a tick for each key and, to evict, sorts by count and then by tick. It runs 3,000 lists of 50 operations on capacities 1 to 3.
ts
import test from'node:test'import assert from'node:assert/strict'import { mulberry32 } from'./rng.ts'import { LfuCache } from'./lfu.ts'
test('ties on use count go to the oldest use', () => {
const c = new LfuCache<number>(2)
c.put('a', 1)
c.put('b', 2)
c.put('c', 3)
assert.equal(c.get('a'), undefined)
assert.equal(c.get('b'), 2)
})
test('capacity 1; an update is a use; bad capacity', () => {
const c = new LfuCache<number>(1)
c.put('a', 1)
c.put('b', 2)
assert.equal(c.get('a'), undefined)
const d = new LfuCache<number>(2)
d.put('a', 1)
d.put('b', 2)
d.put('a', 10)
d.put('c', 3)
assert.equal(d.get('b'), undefined)
assert.equal(d.get('a'), 10)
assert.throws(() => new LfuCache<number>(0), RangeError)
})
ts
type Row = { value: number; uses: number; tick: number }
test('3,000 random lists match a model of counts and ticks', () => {
const rand = mulberry32(101)
for (let t = 0; t < 3000; t++) {
const cap = 1 + Math.floor(rand() * 3)
const c = new LfuCache<number>(cap)
const model = new Map<string, Row>()
let tick = 0
✔ ties on use count go to the oldest use (1.0461ms)
✔ capacity 1; an update is a use; bad capacity (0.5561ms)
✔ 3,000 random lists match a model of counts and ticks (93.5665ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0
Output of one run; the millisecond figures vary
Every operation costs O(1) on average: a few map and set operations, with no scan. Memory is O(capacity). The class also shows the pattern of the whole chapter: each operation's cost sets the choice of container, and the class's job is to keep the containers consistent.