Suppose a job runner keeps its tasks in an array. Every minute, it removes the tasks that are done and takes the next task off the front. Save both jobs, written the obvious way, as opening-slow.ts:
// A job runner keeps its tasks in an array. Remove the done ones, and take tasks off the front.
import { bench } from "./bench.ts";
export type Task = { id: number; done: boolean };
export function makeTasks(n: number): Task[] {
const tasks: Task[] = [];
for (let i = 0; i < n; i++) tasks.push({ id: i, done: i % 2 === 0 }); // every other task is done
return tasks;
}
// Each splice(i, 1) moves every task after i one slot left.
export function removeDone(tasks: Task[]): Task[] {
for (let i = tasks.length - 1; i >= 0; i--) {
if (tasks[i].done) tasks.splice(i, 1);
}
return tasks;
}
// Takes every task off the front with shift(), and adds up their IDs.
export function drainFront(tasks: Task[]): number {
let sum = 0;
while (tasks.length > 0) sum += tasks.shift()!.id;
return sum;
}
if (process.argv[1] === import.meta.filename) {
bench("removeDone with splice", [25_000, 50_000, 100_000], makeTasks, removeDone);
bench("drainFront with shift", [25_000, 50_000, 100_000], makeTasks, drainFront);
}
In one run on 500,000 tasks, removeDone took 15 seconds and drainFront took 22 seconds. The versions you’ll write in this module took 3 and 4 milliseconds on the same tasks.
Both functions remove items from an array, and every removal moves the items behind it. This module keeps the tasks in a linked list instead, where a removal changes one link, and then uses a list to build a cache. It also shows when a plain array does the same job with less code.
After this module, you can:
- remove items from the front or middle of a sequence without moving the rest, with a list or with
filterand an index, and say what each costs - write list code with a dummy head, and reverse a list in place without losing nodes
- use fast and slow pointers to find the middle of a list, and to find where a cycle starts in O(1) memory
- build an LRU cache from a
Mapand a doubly linked list, and say when aMapalone is enough
Measure splice and shift on a growing task list
Make a folder for the module, as in Module 1, and copy bench.ts into it unchanged:
mkdir module-04 && cd module-04 && echo '{ "type": "module" }' > package.json
The if block at the end of opening-slow.ts runs only when you run the file itself, so other files can import its functions.
Pause and predict. removeDone removes half the tasks with splice, and drainFront removes every task with shift. When the list doubles, how many times longer does each one take?
Here is what node opening-slow.ts printed:
removeDone with splice
n median ms x prev
25,000 9.57
50,000 37.90 4.0
100,000 175.42 4.6
drainFront with shift
n median ms x prev
25,000 32.44
50,000 174.86 5.4
100,000 820.92 4.7
Every number in this module comes from one run on an Intel Core i7-9750H laptop (x86_64, 6 cores, macOS) with Node.js 26.13.1. Your numbers will differ, but the ratios should look alike.
Both grow about 4 to 5 times each time the list doubles, so both are O(n²). So twice the tasks cost about four times the time, and ten times the tasks cost about a hundred times.
splice(i, 1) moves every task after i one slot left. removeDone makes n/2 splices, and each one moves about n/2 tasks on average. So it moves about n²/4 tasks in total.
drainFront is O(n²) for a reason Module 1 showed. V8, the JavaScript engine inside Node.js, can remove the first element of a small array without moving the others. It can’t do that for an array over about 16,000 elements. All three sizes here are larger, so every shift moves every remaining task, about n²/2 moves in all.
A linked list: each task in its own node
An array keeps its elements in one block of memory, in order. That’s what makes tasks[i] fast, and it’s also why a removal must close the gap by moving everything behind it.
A list can keep each task in its own small object that points to the next task. Save list.ts:
// A singly linked list node and two helpers used by the module's code and tests.
export type ListNode<T> = { value: T; next: ListNode<T> | null };
export function fromArray<T>(values: T[]): ListNode<T> | null {
let head: ListNode<T> | null = null;
for (let i = values.length - 1; i >= 0; i--) head = { value: values[i], next: head };
return head;
}
export function toArray<T>(head: ListNode<T> | null): T[] {
const out: T[] = [];
for (let node = head; node !== null; node = node.next) out.push(node.value);
return out;
}
A linked list is a sequence in which every item sits in its own object, called a node. Each node holds the item and a pointer to the next node: its next field, a reference to that node’s object. The head is the first node, and the last node’s next is null. Figure 1 draws four tasks as a list, two of them done.
[0 done] -> [1] -> [2 done] -> [3] -> null
^
head
Figure 1: a list has no indexes, only nodes and the links between them, so you reach a task by following links from the head.
That gives a list the opposite costs of an array. Reading the item at position i means following i links, O(i). But removing the node after one you already hold is one pointer write, node.next = node.next.next, and no other node moves. That’s O(1), a cost that stays the same however long the list is.
So a list gives up fast reads by position to get fast removals.
Unlink the done tasks with a dummy head
To remove a node, you change the next of the node before it. The first node has no node before it, so code that removes nodes usually needs a special case for the head. A placeholder node removes that case.
Save opening-fast.ts, starting with the imports and removeDoneList:
// The same two jobs on a linked list, and the plain-array answer (filter, head index).
import { bench } from "./bench.ts";
import { fromArray, type ListNode } from "./list.ts";
import { makeTasks, type Task } from "./opening-slow.ts";
// O(n): unlinking a node changes one pointer; a dummy head means the first node is not a special case.
export function removeDoneList(head: ListNode<Task> | null): ListNode<Task> | null {
const dummy: ListNode<Task> = { value: { id: -1, done: false }, next: head };
let prev = dummy;
while (prev.next !== null) {
if (prev.next.value.done) prev.next = prev.next.next; // unlink, do not move prev
else prev = prev.next;
}
return dummy.next;
}
A dummy head is a node you put before the real head, so that every real node, the first one included, has a node before it. prev starts at the dummy, and the function returns dummy.next, which is the new head.
list-demo.ts, in the module’s folder, prints the list after each step of the loop. Figure 2 traces removeDoneList on the tasks from Figure 1.
start [dummy] -> [0 done] -> [1] -> [2 done] -> [3] -> null
^ prev
step 1 [dummy] -> [1] -> [2 done] -> [3] -> null 0 is done: unlink it
^ prev
step 2 [dummy] -> [1] -> [2 done] -> [3] -> null 1 is open: move prev
^ prev
step 3 [dummy] -> [1] -> [3] -> null 2 is done: unlink it
^ prev
step 4 [dummy] -> [1] -> [3] -> null 3 is open: move prev
^ prev
end prev.next is null, so return dummy.next, which is [1]
Figure 2: prev never moves onto a node it unlinked, so it checks the new prev.next in the next step.
Why does prev stay put after an unlink?
Because the node that slides into prev.next hasn’t been checked yet. After step 1, prev.next is task 1, and step 2 checks it. Every step either unlinks one node or moves prev one node, so the loop runs at most n times. That makes removeDoneList O(n) time with O(1) extra memory.
Taking a task off the front of a list is one pointer move, head = head.next. Add drainList:
// O(n): taking the head is one pointer move.
export function drainList(head: ListNode<Task> | null): number {
let sum = 0;
while (head !== null) {
sum += head.value.id;
head = head.next;
}
return sum;
}
Each task costs O(1), so draining n tasks is O(n).
The array answer, without a list
There’s a second way to fix the opening, and it needs no list. Add two array versions and the benchmark block:
// O(n), and no list needed: build a new array of the tasks to keep.
export const removeDoneFilter = (tasks: Task[]): Task[] => tasks.filter((t) => !t.done);
// O(n): read from a moving index instead of removing.
export function drainIndex(tasks: Task[]): number {
let sum = 0;
for (let i = 0; i < tasks.length; i++) sum += tasks[i].id;
return sum;
}
if (process.argv[1] === import.meta.filename) {
const sizes = [25_000, 50_000, 100_000];
const listOf = (n: number) => fromArray(makeTasks(n));
bench("removeDone on a linked list", sizes, listOf, removeDoneList);
bench("removeDone with filter", sizes, makeTasks, removeDoneFilter);
bench("drainFront on a linked list", sizes, listOf, drainList);
bench("drainFront with an index", sizes, makeTasks, drainIndex);
const big = [1_000_000, 2_000_000, 4_000_000];
bench("removeDone on a linked list (large)", big, listOf, removeDoneList);
bench("removeDone with filter (large)", big, makeTasks, removeDoneFilter);
}
filter builds a new array of the tasks to keep, in one pass. drainIndex reads the tasks in order with an index and removes nothing.
Pause and predict. filter allocates a new array, and removeDoneList only changes pointers. At 100,000 tasks, how far apart do you expect them to be?
Run node opening-fast.ts:
removeDone on a linked list
n median ms x prev
25,000 0.10
50,000 0.20 2.0
100,000 0.51 2.5
removeDone with filter
n median ms x prev
25,000 0.51
50,000 0.70 1.4
100,000 1.37 1.9
drainFront on a linked list
n median ms x prev
25,000 0.13
50,000 0.22 1.7
100,000 0.50 2.3
drainFront with an index
n median ms x prev
25,000 0.06
50,000 0.13 2.3
100,000 0.36 2.9
removeDone on a linked list (large)
n median ms x prev
1,000,000 7.15
2,000,000 14.01 2.0
4,000,000 31.51 2.2
removeDone with filter (large)
n median ms x prev
1,000,000 16.05
2,000,000 78.95 4.9
4,000,000 123.35 1.6
All four are O(n). At 100,000 tasks, unlinking took 0.51 ms where splice took 175.42 ms, about 340 times less. Figure 3 draws removeDone both ways at the same three sizes.
median ms at each n (each # is about 3.9 ms)
n = 25,000 splice ## 9.57
list | 0.10
n = 50,000 splice ########## 37.90
list | 0.20
n = 100,000 splice ############################################# 175.42
list | 0.51
Figure 3: splice grows about 4 times per doubling and unlinking about 2 times, so the gap doubles with every doubling.
But the list did not win by much against filter and the index, and its numbers leave out a cost. bench.ts builds the list before it starts the clock. Your tasks arrived as an array, so building the list is one more O(n) pass and one object per task.
So if your tasks arrive as an array, filter and a read index fix the opening without a list. A list is worth it when you keep references to its nodes and remove or move them many times. The cache later in this module is that case.
Rule: Removing from the front or middle of a large array moves everything behind it. Rebuild with
filter, read with an index, or unlink nodes in a list.
Reverse a list in place
Suppose an editor keeps its undo steps in a list, oldest first, and you want them newest first. You can reverse the list without building a new one, by turning every next pointer around.
The loop keeps three pointers:
previs the head of the part already reversed.nodeis the next node to turn around.nextholds the rest of the list.
Figure 4 traces it on three undo steps.
step next saved reversed part (prev) node
start - null [type]
1 [bold] [type] -> null [bold]
2 [delete] [bold] -> [type] -> null [delete]
3 null [delete] -> [bold] -> [type] -> null null
Figure 4: each step turns one node around and adds it to the front of the reversed part, so prev ends as the new head.
Save reverse.ts:
import type { ListNode } from "./list.ts";
// O(n) time, O(1) memory: each node's next is flipped once.
export function reverseList<T>(head: ListNode<T> | null): ListNode<T> | null {
let prev: ListNode<T> | null = null;
let node = head;
while (node !== null) {
const next = node.next; // save before overwriting
node.next = prev;
prev = node;
node = next;
}
return prev;
}
node.next = prev overwrites the only link to the rest of the list, so the line before it saves that link in next. The common mistakes section shows what happens without that line.
Each node is visited once, so reverseList is O(n) time with O(1) extra memory. reverse.test.ts checks a list of 100,000 nodes. Run it with node --test reverse.test.ts.
Fast and slow pointers
To find the middle of an array, you read its length. A list has no stored length, so the obvious way is two passes, one to count and one to walk half. One pass is enough if two pointers walk at different speeds.
Fast and slow pointers are two pointers that start at the head, where fast moves two nodes per step and slow moves one. When fast reaches the end, slow has walked half as far. Save fast-slow.ts, starting with middleNode:
import type { ListNode } from "./list.ts";
// Fast and slow pointers: fast moves two nodes per step, slow moves one.
// The middle node in one pass. O(n) time, O(1) memory.
// For an even length this returns the second of the two middle nodes.
export function middleNode<T>(head: ListNode<T> | null): ListNode<T> | null {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow!.next;
fast = fast.next.next;
}
return slow;
}
Pause and predict. For the list [1] -> [2] -> [3] -> [4], where is slow when the loop stops?
Figure 5 traces both lengths, as list-demo.ts prints them.
odd: [1] -> [2] -> [3] -> [4] -> [5] -> null
start slow 1, fast 1
step 1 slow 2, fast 3
step 2 slow 3, fast 5 fast.next is null: stop, middle is 3
even: [1] -> [2] -> [3] -> [4] -> null
start slow 1, fast 1
step 1 slow 2, fast 3
step 2 slow 3, fast null fast is null: stop, middle is 3
Figure 5: fast walks twice as far as slow, so when fast reaches the end, slow is halfway.
For four nodes, slow stops at 3, the second of the two middle nodes. The loop checks fast !== null, which ends an even-length list, and fast.next !== null, which ends an odd-length one. Leave out the first check, and an even length crashes. middleNode walks n/2 steps, so it is O(n) time with O(1) memory.
Find a cycle in O(1) memory
Now suppose each node is a page in a chain of redirects, and each page points to the next. A wrong setting can make the chain come back to a page it already passed. A list has a cycle when following next from the head reaches a node it already passed, so it never reaches null.
You could keep every node you’ve visited in a Set, as in Module 3, and stop at the first node already in it. That’s O(n) time and O(n) memory. Fast and slow pointers find a cycle with O(1) memory. Add hasCycle to fast-slow.ts:
// Does following next from the head ever come back to a node it passed? O(n) time, O(1) memory.
// Without a cycle, fast reaches the end. With one, fast gains one node per step on slow, so they meet.
export function hasCycle<T>(head: ListNode<T> | null): boolean {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow!.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}
Without a cycle, fast reaches the end, as in middleNode. With a cycle, both pointers end up going around it. Each step, fast moves one node closer to slow, so the distance between them shrinks by exactly one and fast can’t jump over slow. They meet before slow has gone once around the cycle, so the loop runs fewer than n steps, O(n) time with O(1) memory.
hasCycle says that there is a cycle, but not where it starts. A second phase finds the first node of the cycle, the page where the chain went wrong. Figure 6 traces both phases on five pages, where /promo points back to /login.
[/old] -> [/new] -> [/login] -> [/home] -> [/promo]
^ |
+-----------------------+ /promo points to /login
phase 1 slow fast
start /old /old
step 1 /new /login
step 2 /login /promo
step 3 /home /home they meet, so there is a cycle
phase 2 a b
start /old /home a starts at the head, b where they met
step 1 /new /promo
step 2 /login /login they meet at the first node of the cycle
Figure 6: after the meeting, a pointer from the head and a pointer from the meeting point, one step at a time, meet where the cycle starts.
Both phases together are Floyd’s cycle detection, usually credited to Robert W. Floyd. Phase 2 walks one step for each node before the cycle, so the whole method stays O(n) time with O(1) memory. Going deeper shows why the two pointers meet exactly at the start. Exercise 3 asks you to write phase 2.
Rule: When a list question needs a position (the middle, a cycle) and O(1) memory, move two pointers at different speeds.
An LRU cache from a Map and a doubly linked list
Suppose a service caches rendered pages, at most N of them. When the cache is full and a new page arrives, it should drop the page that was read or written longest ago. An LRU cache (least recently used) is a cache that does exactly that. To evict a key is to drop it from a cache to make room.
The short version: a Map alone
Module 3 showed that a Map iterates in insertion order. set on a new key appends it at the end, so delete followed by set moves a key to the end. The first key is then the least recently used one. Save lru-map-only.ts:
// The shortcut: a Map alone is an LRU cache, because a Map iterates in insertion order.
// delete + set moves a key to the end; the first key is the least recently used.
export class LruMap<K, V> {
private map = new Map<K, V>();
private capacity: number;
constructor(capacity: number) {
this.capacity = capacity;
}
get size(): number {
return this.map.size;
}
get(key: K): V | undefined {
if (!this.map.has(key)) return undefined;
const value = this.map.get(key)!;
this.map.delete(key);
this.map.set(key, value);
return value;
}
put(key: K, value: V): void {
if (this.map.has(key)) this.map.delete(key);
else if (this.map.size === this.capacity) this.map.delete(this.map.keys().next().value!);
this.map.set(key, value);
}
keys(): K[] {
return [...this.map.keys()].reverse();
}
}
It’s correct, and it’s short. this.map.keys().next().value is the first key, the one to evict. Its cost is measured below, after the version that uses a list.
The classic version: a Map and a list
The classic design keeps the keys in a list ordered from most to least recently used, and a Map from each key to its node. The Map finds a node in O(1). Moving that node to the front means unlinking it from wherever it sits, and for that you need the node before it.
A doubly linked list is a list whose nodes also point to the previous node, so you can unlink a node you hold in O(1), without walking from the head. The tail is the last node. Here the head is the most recently used key and the tail the least recently used one. Save lru-cache.ts:
// An LRU cache from a Map and a doubly linked list. get and put are O(1) on average.
// Memory per cached key: one Map entry and one node object (see memory.ts).
type Node<K, V> = { key: K; value: V; prev: Node<K, V> | null; next: Node<K, V> | null };
export class LruCache<K, V> {
private map = new Map<K, Node<K, V>>();
private head: Node<K, V> | null = null; // most recently used
private tail: Node<K, V> | null = null; // least recently used
private capacity: number;
constructor(capacity: number) {
if (capacity < 1) throw new RangeError("capacity must be at least 1");
this.capacity = capacity;
}
get size(): number {
return this.map.size;
}
get(key: K): V | undefined {
const node = this.map.get(key);
if (node === undefined) return undefined;
this.unlink(node);
this.pushFront(node);
return node.value;
}
put(key: K, value: V): void {
const old = this.map.get(key);
if (old !== undefined) {
old.value = value;
this.unlink(old);
this.pushFront(old);
return;
}
if (this.map.size === this.capacity) {
const lru = this.tail!;
this.unlink(lru);
this.map.delete(lru.key);
}
const node: Node<K, V> = { key, value, prev: null, next: null };
this.pushFront(node);
this.map.set(key, node);
}
// Keys from most to least recently used, for tests.
keys(): K[] {
const out: K[] = [];
for (let n = this.head; n !== null; n = n.next) out.push(n.key);
return out;
}
private unlink(node: Node<K, V>): void {
if (node.prev !== null) node.prev.next = node.next;
else this.head = node.next;
if (node.next !== null) node.next.prev = node.prev;
else this.tail = node.prev;
node.prev = node.next = null;
}
private pushFront(node: Node<K, V>): void {
node.next = this.head;
if (this.head !== null) this.head.prev = node;
this.head = node;
if (this.tail === null) this.tail = node;
}
}
Each node stores its key, so that eviction can delete the tail’s key from the Map. unlink and pushFront handle the head and the tail with if statements, because this list has no dummy nodes. Figure 7 traces a cache with room for two keys.
operation list after it, head first Map holds evicted
put a [a] a
put b [b] <-> [a] a, b
get a [a] <-> [b] a, b
put c [c] <-> [a] a, c b, the tail
Figure 7: get moves a node to the head and put evicts the tail, so the tail is always the least recently used key.
get is one Map lookup and a few pointer writes. put is the same, plus one Map delete when it evicts. Both are O(1) on average, and the memory is one Map entry and one node per key. Run node --test lru-cache.test.ts to check the cache against a slow but simple reference over 2,000 random operations.
Measure both caches
lru-bench.ts runs 200,000 operations on caches of three capacities, in two workloads:
- “All misses” puts a new key every time, so every put past the capacity evicts.
- “Mixed” reads random keys from twice the capacity and puts each key it misses, so about half the operations evict.
// 200,000 operations on an LRU cache of several capacities, Map + list against Map only.
import { bench } from "./bench.ts";
import { LruCache } from "./lru-cache.ts";
import { LruMap } from "./lru-map-only.ts";
const OPS = 200_000;
type Cache = { get(k: number): number | undefined; put(k: number, v: number): void };
// Every put is a new key, so every put past the capacity evicts.
function allMisses(c: Cache): void {
for (let i = 0; i < OPS; i++) c.put(i, i);
}
// Random keys from 2 x capacity: about half the gets miss, and each miss puts and evicts.
function mixed(c: Cache & { cap: number }): void {
for (let i = 0; i < OPS; i++) {
const k = Math.floor(Math.random() * 2 * c.cap);
if (c.get(k) === undefined) c.put(k, i);
}
}
const caps = [1_000, 4_000, 16_000];
const list = (cap: number) => Object.assign(new LruCache<number, number>(cap), { cap });
const mapOnly = (cap: number) => Object.assign(new LruMap<number, number>(cap), { cap });
bench("all misses, Map + linked list (n = capacity)", caps, list, allMisses);
bench("all misses, Map only", caps, mapOnly, allMisses);
bench("mixed, Map + linked list", caps, list, mixed);
bench("mixed, Map only", caps, mapOnly, mixed);
Pause and predict. Every operation of both caches is a few Map calls. When the capacity grows from 1,000 to 16,000, what happens to the time for 200,000 operations?
Run node lru-bench.ts:
all misses, Map + linked list (n = capacity)
n median ms x prev
1,000 14.88
4,000 24.10 1.6
16,000 20.26 0.8
all misses, Map only
n median ms x prev
1,000 72.28
4,000 253.68 3.5
16,000 952.32 3.8
mixed, Map + linked list
n median ms x prev
1,000 14.36
4,000 16.43 1.1
16,000 19.45 1.2
mixed, Map only
n median ms x prev
1,000 37.48
4,000 89.96 2.4
16,000 286.08 3.2
The list version took about the same time at every capacity, as O(1) per operation predicts. The Map-only version grew with the capacity in both workloads. When every put evicted, it grew about 4 times for each 4 times more capacity. At 16,000 it took 952.32 ms against 20.26 ms, so its eviction costs O(capacity), not O(1).
Why does dropping the oldest key get slower as the cache grows?
Module 3 showed that delete marks an entry as deleted and leaves it in place until V8 rebuilds the table. The cache always evicts the oldest key, so the deleted entries pile up at the front of the table. A fresh keys() iterator starts at the front and steps over every one of them.
Figure 8 shows a cache of 4 keys after putting the keys 1 to 8, when the table has grown to 8 slots.
Map entries before put(9)
[deleted] [deleted] [deleted] [5] [6] [7] [8] [free]
0 1 2 3 4 5 6 7
^ keys() starts here, steps over 0, 1 and 2, and returns 5
Figure 8: in a Map that keeps evicting its oldest key, the deleted entries collect at the front, and every fresh iterator walks over them.
A bigger cache piles up more deleted entries between rebuilds, so each eviction walks further. Going deeper gives the V8 rule behind that.
So the choice depends on how often the cache evicts. The Map-only version is less than half the code, and it scans only when it evicts, so it’s fine for a cache that rarely fills up. When the cache stays full and puts evict, use the Map and the list. The list costs one 56-byte node per key, as the section on memory shows.
Rule: An LRU cache needs O(1) lookup and O(1) “move to front” and “drop the oldest”. A
Mapgives the first, and a doubly linked list gives the other two.
Two more shapes of list code
The patterns above come up in two more shapes. Each has a sign in the problem that points to it.
Two pointers a fixed distance apart
Suppose a log is a list of entries from oldest to newest, and you want the entry 2 places from the end. Fast and slow pointers keep a growing distance between them. Here the two pointers keep a fixed one.
Let lead walk k nodes first. Then move lead and trail one node at a time until lead is null. trail is then k nodes from the end, because it is always k nodes behind lead. Figure 9 traces k = 2 on five log entries.
[boot] -> [login] -> [upload] -> [logout] -> [shutdown] -> null
start trail boot, lead upload lead walked k = 2 nodes first
step 1 trail login, lead logout
step 2 trail upload, lead shutdown
step 3 trail logout, lead null stop: logout is 2nd from the end
Figure 9: trail stays k nodes behind lead, so when lead is null, trail is k nodes from the end.
It walks the list once, O(n) time, with O(1) memory. Counting the length first and then walking n − k nodes is also O(n), but in two passes. The sign is “k-th from the end” or “in one pass”. Exercise 1 asks you to write it.
A dummy head to build a list
A dummy head also helps when you build a list instead of removing from one. Keep a tail pointer to the last node, and append with tail = tail.next = node. Because the dummy is there, the first append is not a special case. splitByDone in variations.ts uses this to split the tasks into the open ones and the done ones, with one dummy head per output list.
For tasks 0 to 4, where the even ones are done, node variations.ts prints open: [ 1, 3 ] done: [ 0, 2, 4 ]. At the end, it sets each tail’s next to null, because the last open task may still point to a done task.
The sign is “split”, “merge” or “build a list from parts of other lists”. Exercise 2 merges two sorted lists this way.
Underneath: what a node costs in V8
The facts in this section hold as of V8 14.6.202.34, the version in Node.js 26.13.1.
memory.ts builds 1,000,000 of each structure and measures how much the heap, the memory where JavaScript objects live, grew. Before each reading, it runs a garbage collection, the step that frees objects nothing points to anymore. Starting one by hand needs a flag, so run node --expose-gc memory.ts.
Pause and predict. An array slot of a small integer takes 8 bytes. How many bytes does one { value, next } node take?
array of small integers: 8.0
singly linked {value, next}: 40.0
doubly linked class DNode: 48.0
Map<number, number> entries: 29.4
LRU node {key, value, prev, next}: 56.0
These are bytes per element. A node of a singly linked list costs 5 times as much as one array slot, and a node of LruCache costs 7 times as much.
Every object in V8 starts with a header of three 8-byte words, followed by its fields, as the V8 blog explains in Fast properties in V8. So { value, next } is 3 + 2 = 5 words, 40 bytes. The LRU node, with four fields, is 7 words, 56 bytes. An array of small integers has no header per element, so it needs one 8-byte slot per element.
In other words, a list pays a header for every item, and an array pays one for the whole block. A list also reads memory out of order when you walk it, and Going deeper explains why that costs time.
Underneath: why app code rarely needs a linked list
The ECMAScript specification’s built-in collections are arrays, typed arrays, Map, Set, WeakMap and WeakSet (ECMAScript). There is no list, and none is proposed in the TC39 proposals. Neither says why, but this module’s numbers show what an array already covers.
In the table, amortized O(1) means that a few calls cost more, such as a push that has to grow the array, but the average over many calls is O(1).
| Job | With an array | With a linked list | Choose the list when |
|---|---|---|---|
| Add or remove at the end (a stack) | push, pop: O(1) amortized |
O(1), 5 times the memory | never for this job |
| Take from the front (a queue) | a read index: O(1) | head = head.next: O(1) |
the queue also needs removals in the middle |
| Remove many items in one pass | filter: O(n) |
unlink: O(n) | the items are already in a list |
| Remove or move a node you hold | O(n): splice moves the rest |
O(1): a few pointer writes | you keep node references and do this often |
| Read or walk the items | O(1) by index, reads in order | O(i) by position, reads out of order | never for this job |
Only the fourth row is a reason to write a list, and that is the LRU cache’s case.
Node.js itself has one such case. Its timers keep one list per duration, so clearTimeout can unlink a timer in O(1). The source calls this “virtually constant-time insertion (append), removal, and timeout”, in lib/internal/timers.js.
Module 5 builds the queue from the second row properly, with a head index and a ring buffer.
What changed recently. For the structures in this module, nothing between Node.js 22 and Node.js 26. The benchmarks in this module that also ran on Node.js 22.17 showed the same growth there. Going deeper names the V8 rules that stayed the same.
Common mistakes
mistakes.ts writes six bugs that are easy to make with lists, and prints what each one returns. Run node mistakes.ts:
1. reverse without saving next: [ 1 ]
2. remove 7 without a dummy head: [ 7, 1, 2 ]
3. remove 7, always advancing prev: [ 1, 7, 2 ]
4. middle of [1,2,3,4]: TypeError: Cannot read properties of null (reading 'next')
5. forward splice of every 7: [ 7, 1, 7, 2 ]
6. keys after reading a, then adding c: [ 'b', 'c' ]
Overwriting next before saving it. The reverse loop sets node.next = prev and then moves to node.next, which is now prev. The loop ends after one node, and [1, 2, 3, 4] comes back as [ 1 ], with the rest of the list lost. Save const next = node.next first, as in reverseList.
Removing without a dummy head. Starting prev at the head means the head itself is never checked. So removing every 7 from [7, 1, 7, 2] leaves the first 7. Start prev at a dummy node, as in removeDoneList.
Moving prev after an unlink. After prev.next = prev.next.next, the new prev.next hasn’t been checked yet. Moving prev skips it, so [1, 7, 7, 2] keeps the second 7. Move prev only when you did not unlink.
Checking only fast.next. On an even length, fast becomes null after its last double step, and fast.next throws a TypeError. Check fast !== null && fast.next !== null, in that order.
Calling splice in a forward loop. After splice(i, 1), the next element moves into index i, and i++ skips it. So removing every 7 from [7, 7, 1, 7, 7, 2] leaves two of them. Loop backwards, as removeDone does, or use filter, which is also O(n) instead of O(n²).
A Map-only LRU whose get doesn’t move the key. get("a") alone leaves a first in insertion order, so the next eviction drops a, the key that was read last. In get, delete the key and set it again, as LruMap does.
Exercises
The exercises are in the module’s exercises folder, each with a test file, and the solutions are in solutions. Run all the tests with:
node --test "exercises/*.test.ts"
All 19 tests fail until you write the four answers. The last test of Exercise 4 also times 200,000 puts, so an answer that is correct but evicts in O(capacity) fails. A Map-only answer passed the other five tests and failed that one with took 3200 ms.
Exercise 1: the k-th newest log entry (easy)
A log is a list of entries from oldest to newest. Write nthFromEnd(head, k): the node k places from the end, where k = 1 is the newest entry, or null if the list has fewer than k entries. Walk the list once. Start from exercises/nth-from-end.ts.
The tests check k = 1, k in the middle, k equal to the length, a list shorter than k, and that you return the node itself.
Hint
Use two pointers k nodes apart, as in Figure 9. Where can lead find out that the list has fewer than k entries?
Solution
import type { ListNode } from "../list.ts";
// Exercise 1: a log is a list of entries from oldest to newest.
// Return the node k places from the end (k = 1 is the newest entry), or null if the list
// has fewer than k entries. Walk the list once and use O(1) extra memory.
// Two pointers k nodes apart: O(n) time, O(1) memory.
export function nthFromEnd<T>(head: ListNode<T> | null, k: number): ListNode<T> | null {
let lead = head;
for (let i = 0; i < k; i++) {
if (lead === null) return null; // fewer than k entries
lead = lead.next;
}
let trail = head;
while (lead !== null) {
lead = lead.next;
trail = trail!.next;
}
return trail;
}
Cost: O(n) time, because lead walks the list once and trail follows it. O(1) extra memory. If lead hits null during its first k moves, the list is shorter than k.
Exercise 2: merge two sorted logs (medium)
Two services each keep a list of log entries sorted by time. Write mergeSorted(a, b): one list sorted by time, built by relinking the existing nodes, not by copying them. When two entries have the same time, the one from a comes first. Start from exercises/merge-sorted.ts.
The tests check the order, equal times, empty lists, and that the result reuses the input nodes.
Hint
Use a dummy head and a tail pointer, as in splitByDone. Each step, attach the earlier of the two front nodes. What do you attach when one list runs out?
Solution
import type { ListNode } from "../list.ts";
export type Entry = { time: number; text: string };
// Exercise 2: merge two lists of log entries, each sorted by time, into one sorted list.
// Relink the existing nodes; on equal times take the entry from `a` first.
// A dummy head and a tail pointer: O(n + m) time, O(1) extra memory.
export function mergeSorted(a: ListNode<Entry> | null, b: ListNode<Entry> | null): ListNode<Entry> | null {
const dummy: ListNode<Entry> = { value: { time: 0, text: "" }, next: null };
let tail = dummy;
while (a !== null && b !== null) {
if (a.value.time <= b.value.time) {
tail.next = a;
a = a.next;
} else {
tail.next = b;
b = b.next;
}
tail = tail.next;
}
tail.next = a !== null ? a : b; // one list is empty; attach the rest of the other
return dummy.next;
}
Cost: O(n + m) time, one step per node. O(1) extra memory, because it relinks the nodes it was given. The <= takes from a on equal times, so entries with equal times keep their original order. When one list runs out, the rest of the other is already sorted, so one link attaches all of it.
Exercise 3: where a redirect chain goes wrong (medium)
Each node is a page in a chain of redirects. Write findCycleStart(head): the first node of the cycle, or null if the chain ends. Use O(1) extra memory, so no Set. Start from exercises/find-cycle.ts.
The tests check a chain that ends, cycles back to the middle and to the head, and a page that points to itself. They also try every cycle position in chains of up to 30 pages.
Hint
Start from hasCycle. Where it returns true, run phase 2 from Figure 6: one pointer from the head, one from the meeting point, one step each.
Solution
import type { ListNode } from "../list.ts";
// Exercise 3: each page in a chain of redirects points to the next one.
// Return the first node of the cycle, or null if the chain ends. Use O(1) extra memory.
// Floyd's cycle detection: O(n) time, O(1) memory.
export function findCycleStart<T>(head: ListNode<T> | null): ListNode<T> | null {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow!.next;
fast = fast.next.next;
if (slow === fast) {
// Phase 2: one pointer from the head, one from the meeting point, one step each.
let a = head;
let b: ListNode<T> | null = slow;
while (a !== b) {
a = a!.next;
b = b!.next;
}
return a;
}
}
return null;
}
Cost: O(n) time. Phase 1 ends in fewer than n steps, and phase 2 walks one step for each node before the cycle. O(1) extra memory, four pointers. When the cycle starts at the head, phase 2 returns at once.
Exercise 4: a cache limited by total size (harder)
Write SizedCache, an LRU cache of response bodies limited by their total size in bytes, not by how many it holds. put(key, value, size) stores the entry as the most recently used, then evicts least recently used entries until the total size is at most maxSize.
An entry larger than maxSize is not stored, and an older entry under the same key is removed. The class also has get, a totalSize getter and keys(), from most to least recently used. Start from exercises/sized-cache.ts.
The tests check eviction of several entries at once, get moving a key, a new size for an existing key, and an entry that is too large. They also compare 3,000 random operations with a slow reference, and time 200,000 puts.
Hint
Start from LruCache. Store the size in each node and keep a running total. A put can evict more than one entry, so evict from the tail in a loop. Why is that loop still amortized O(1) per put?
Solution
// Exercise 4: a cache of response bodies, limited by their total size instead of their count.
// put(key, value, size) stores the entry as the most recently used, then evicts least recently
// used entries until the total size is at most maxSize. An entry larger than maxSize is not
// stored, and an older entry under the same key is removed. get makes a key the most recently used.
// A Map from key to node, and a doubly linked list from most to least recently used.
// get: O(1). put: O(1) plus one step per evicted entry; each entry is evicted at most once,
// so amortized O(1). Memory: O(number of entries).
type Node<K, V> = { key: K; value: V; size: number; prev: Node<K, V> | null; next: Node<K, V> | null };
export class SizedCache<K, V> {
private map = new Map<K, Node<K, V>>();
private head: Node<K, V> | null = null; // most recently used
private tail: Node<K, V> | null = null; // least recently used
private maxSize: number;
private total = 0;
constructor(maxSize: number) {
this.maxSize = maxSize;
}
get totalSize(): number {
return this.total;
}
get(key: K): V | undefined {
const node = this.map.get(key);
if (node === undefined) return undefined;
this.unlink(node);
this.pushFront(node);
return node.value;
}
put(key: K, value: V, size: number): void {
const old = this.map.get(key);
if (old !== undefined) this.remove(old);
if (size > this.maxSize) return;
const node: Node<K, V> = { key, value, size, prev: null, next: null };
this.pushFront(node);
this.map.set(key, node);
this.total += size;
while (this.total > this.maxSize) this.remove(this.tail!);
}
keys(): K[] {
const out: K[] = [];
for (let n = this.head; n !== null; n = n.next) out.push(n.key);
return out;
}
private remove(node: Node<K, V>): void {
this.unlink(node);
this.map.delete(node.key);
this.total -= node.size;
}
private unlink(node: Node<K, V>): void {
if (node.prev !== null) node.prev.next = node.next;
else this.head = node.next;
if (node.next !== null) node.next.prev = node.prev;
else this.tail = node.prev;
node.prev = node.next = null;
}
private pushFront(node: Node<K, V>): void {
node.next = this.head;
if (this.head !== null) this.head.prev = node;
this.head = node;
if (this.tail === null) this.tail = node;
}
}
Cost: get is O(1) on average. One put can evict many entries, but every entry is evicted at most once after the put that added it. So over any run of puts, evictions never outnumber puts, and put is amortized O(1), the argument Module 1 made for push. Memory is one Map entry and one node per stored entry.
Removing the old entry first, before the size check, is what makes a too-large put drop the old value.
Going deeper
You can skip this section. It holds the proof, the V8 details and the extra benchmark that the main path left out.
Why phase 2 meets at the start of the cycle
Say m nodes come before the cycle (/old and /new in Figure 6, so m = 2). The cycle has c nodes (/login, /home, /promo, so c = 3). Phase 1 met after k = 3 steps, when fast had walked 2k nodes and slow k. The extra k nodes fast walked were whole trips around the cycle, so k is a multiple of c.
In phase 2, a walks m steps from the head and stops on the first node of the cycle. In the same m steps, b walks from the meeting point, so it has walked k + m steps from the head in total. That’s m steps plus whole trips around the cycle, which puts b on the same first node. They can’t meet earlier, because until then a is still outside the cycle and b is inside it.
Why a Map-only cache slows down in V8
In V8 14.6, the table settles at a capacity of at least twice the cache’s size. So between rebuilds, the deleted entries grow to at least the cache’s size. Each eviction walks over a share of them that grows with the capacity.
The iterator code is NextSkipHashTableHoles in builtins-collections-gen.cc. The rebuild rule is EnsureCapacityForAdding in ordered-hash-table.cc.
Where the node sizes come from
A small integer that V8 stores right inside its slot is a Smi (Module 2), so value: i costs no extra object. The Map entry is the 28 bytes per slot from Module 3, plus the unused part of the table.
These sizes assume 8-byte pointers. process.config.variables.v8_enable_pointer_compression is 0 in Node.js 26.13.1. So, as Module 1 said, Node.js on x64 is still built without pointer compression, which stores each pointer in 4 bytes. Chrome compresses pointers, as the V8 blog explains in Pointer compression in V8. So in Chrome, every one of these sizes should be about half, and the ratios should stay the same.
Walking a list reads memory out of order
An array of small integers keeps its values in one block, so a loop reads memory in order. A list keeps each value in a separate object, and each step reads a pointer to find the next one. walk.ts in the lab folder times both, and a list whose nodes were linked in a shuffled order walks far slower than one built in order.
A list that gains and loses nodes over a long time links nodes that were allocated at different times. So its neighbors need not sit next to each other in memory, and a walk over it can cost more than a walk over a fresh list.
The V8 rules that stayed the same
Both V8 12.4 (Node.js 22) and V8 14.6 (Node.js 26) refuse to left-trim an array in large-object space. Left-trimming drops the first element by moving the array’s start, and large-object space is where V8 keeps very large objects. The check is CanMoveObjectStart in heap.cc. Both versions also leave deleted Map entries in place until the table is rebuilt.
Cheat sheet
Figure 10 is the summary of the module: which shape fits which sign in a problem.
sign in the problem shape cost
remove or move items you hold, often list + node references O(1) each
"remove every X" from a list dummy head, move prev O(n)
"newest first" from a list, in place prev, node, next O(n)
the middle, in one pass fast and slow pointers O(n)
"does it come back?" in O(1) memory Floyd, then phase 2 O(n)
"k-th from the end", in one pass two pointers k apart O(n)
evict the least recently used Map + doubly linked list O(1) each
Figure 10: a list is worth its memory only when you hold its nodes and change the links around them, and every shape above is a loop of pointer moves.
- Linked list: reading position i is O(i), and unlinking after a node you hold is O(1). A node costs 40 bytes in Node.js on x64, an array slot 8.
- Dummy head: start
prevat a node before the head, move it only when you don’t unlink, and returndummy.next. - Reverse and fast/slow: save
nextbefore you overwrite it, and loop whilefast !== null && fast.next !== null. - LRU cache: a
Mapfrom key to node plus a doubly linked list is O(1). AMapalone is fine only if it rarely evicts. - Arrays first:
filterand a read index fix most front and middle removals without a list. - Next: Module 5 turns the array into a stack and a queue, and builds a queue that never calls
shift().
Sources
- V8 source at 14.6.202.34, the version in Node.js 26.13.1:
heap-object.tqandjs-objects.tq(object header),builtins-collections-gen.cc(NextSkipHashTableHoles,Map.prototype.delete),ordered-hash-table.cc(EnsureCapacityForAdding),heap.cc(CanMoveObjectStart),elements.cc(shiftand left-trimming). - V8 blog: Fast properties in V8 (2017), Pointer compression in V8 (2020).
- Node.js 26.13.1 source:
lib/internal/timers.jsandlib/internal/linkedlist.js. - ECMAScript specification:
Map.prototype.set,Map.prototype.delete,Array.prototype.splice; TC39 proposals.