Suppose a service hands its jobs to a worker through a queue. New jobs go in at the back with push(), and the worker takes the next job from the front with shift(). Save this queue and a benchmark for it as opening-slow.ts:
// Opening problem: a work queue on push() and shift(). The backlog holds n jobs;
// each round takes one job off the front and adds a new one at the back.
import { bench } from "./bench.ts";
export type Job = { id: number };
export const ROUNDS = 100_000;
export function makeBacklog(n: number): Job[] {
const q: Job[] = [];
for (let i = 0; i < n; i++) q.push({ id: i });
return q;
}
// Once the array passes about 15,000 jobs, each shift() moves every remaining job one slot left.
export function runArrayQueue(q: Job[]): number {
let sum = 0;
for (let i = 0; i < ROUNDS; i++) {
sum += q.shift()!.id;
q.push({ id: i });
}
return sum;
}
if (process.argv[1] === import.meta.filename) {
bench(`array queue, ${ROUNDS} rounds (n = jobs waiting)`, [10_000, 20_000, 40_000, 80_000], makeBacklog, runArrayQueue);
}
bench is the timing script from Module 1. It runs a function on inputs of several sizes and prints the median time for each size. Here each input is a backlog of n waiting jobs, and each round takes one job and adds one, so n stays the same for the whole run.
In one run with 200,000 jobs waiting, the 100,000 rounds took 3.6 seconds. The two queues you’ll write in this module did the same work in about 5 milliseconds.
This module builds a queue that never calls shift(), first with a head index and then with a ring buffer. It also uses the end of the array as a stack. Then it builds two patterns on top of these structures, the monotonic stack and the window maximum.
After this module, you can:
- use an array as a stack, and say why
pushandpopare O(1) whileshiftandunshiftare not - build a queue with a head index or a ring buffer that stays O(1) per operation at any length, and say what memory each one costs
- find the next larger value for every item in O(n) with a monotonic stack
- find the maximum of every window of k items in O(n) with a deque
Measure a queue built on shift()
Make a folder for the module, as in Module 1, and copy bench.ts into it unchanged:
mkdir module-05 && cd module-05 && echo '{ "type": "module" }' > package.json
Pause and predict. A round is one shift and one push. When the waiting jobs double from 10,000 to 20,000, how much longer do the 100,000 rounds take? And from 40,000 to 80,000?
Here is what node opening-slow.ts printed:
array queue, 100000 rounds (n = jobs waiting)
n median ms x prev
10,000 7.22
20,000 228.11 31.6
40,000 597.39 2.6
80,000 1409.12 2.4
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.
At 10,000 jobs, a round took about 72 nanoseconds. Then the time jumped 31.6 times for one doubling. Why would one doubling cost 31 times more?
Module 1 showed the reason. V8 is the JavaScript engine inside Node.js. While an array’s memory is under 128 KB, V8 runs shift() by moving the start of the array one slot forward, so no element moves. An array built with push passes 128 KB at about 15,000 elements, and from then on shift() copies every remaining element one slot left.
Module 1 called this jump the cliff. Above it, one round is O(n), which means its time grows in step with the n waiting jobs. The last two doublings took 2.6 and 2.4 times longer, close to the 2 that O(n) predicts.
A queue on shift() is fast in a test with a few hundred jobs, and slow when a backlog builds up, which is when you need it most.
A stack: push and pop at the same end
Before fixing the front of the array, look at its end. push adds there and pop removes from there, and neither moves any other element. So both are O(1), which means their cost doesn’t depend on the array’s length.
For push, that cost is amortized O(1). Once in a while it copies the array into a larger block of memory. But averaged over many pushes, the cost per push stays the same at any length.
A stack is a sequence where you add and remove items at the same end, so the last item in is the first one out. The end you use is the top. An array is a stack as it is: push adds to the top, pop removes it, and at(-1) reads it without removing it.
A stack fits any job where the most recent open thing must close first. Suppose a trace log records spans, timed pieces of work such as a database call, each with a start event and an end event. Spans nest, and every end closes the span that started most recently. Save spans.ts:
// A trace log of nested spans: every "end" closes the span that started most recently.
export type SpanEvent = { kind: "start" | "end"; name: string; t: number };
// Each span's duration, in the order the spans end.
// A stack of open spans: O(n) time, O(d) memory for spans nested d deep.
export function spanDurations(events: SpanEvent[]): string[] {
const open: SpanEvent[] = [];
const out: string[] = [];
for (const e of events) {
if (e.kind === "start") {
open.push(e);
continue;
}
const start = open.pop(); // the most recent open span
if (start === undefined || start.name !== e.name) throw new Error(`end ${e.name} does not match`);
out.push(`${e.name} ${e.t - start.t} ms`);
}
if (open.length > 0) throw new Error(`${open.at(-1)!.name} never ended`);
return out;
}
if (process.argv[1] === import.meta.filename) {
const log: SpanEvent[] = [
{ kind: "start", name: "request", t: 0 },
{ kind: "start", name: "db", t: 2 },
{ kind: "end", name: "db", t: 9 },
{ kind: "start", name: "render", t: 10 },
{ kind: "end", name: "render", t: 14 },
{ kind: "end", name: "request", t: 15 },
];
console.log(spanDurations(log));
}
node spans.ts prints [ 'db 7 ms', 'render 4 ms', 'request 15 ms' ]. Figure 1 shows the stack after each event of that log, as trace-demo.ts prints it.
event open spans, top on the right
start request [request]
start db [request] [db]
end db [request] db: 9 - 2 = 7 ms
start render [request] [render]
end render [request] render: 14 - 10 = 4 ms
end request (empty) request: 15 - 0 = 15 ms
Figure 1: every end pops the span on top, which is the one that started most recently, so nesting needs no search.
The two checks matter as much as the stack. pop() on an empty array returns undefined, so an end with nothing open shows up as start === undefined. And a span still on the stack after the loop never ended.
Each event is one push or one pop, so spanDurations is O(n) time for n events. The stack holds only the open spans, so its memory is O(d) for spans nested d deep. spans.test.ts checks 100,000 spans nested inside each other.
Rule: When the most recent open item must be the first to close, keep the open items on a stack.
A queue with a head index
A queue is a sequence where you add items at one end and remove them from the other, so the first item in is the first one out. The opening’s array is a queue, and its slow part is removing from the front.
But you don’t have to remove the front item. You can leave it where it is and move an index past it. Save index-queue.ts:
// A queue on an array with a head index. push and shift are amortized O(1).
export class IndexQueue<T> {
private items: (T | undefined)[] = [];
private head = 0; // index of the front item
get size(): number {
return this.items.length - this.head;
}
push(item: T): void {
this.items.push(item);
}
shift(): T | undefined {
if (this.head === this.items.length) return undefined;
const item = this.items[this.head];
this.items[this.head] = undefined; // let the garbage collector free the job
this.head++;
// Once the used front is over half the array, copy the rest to a new array:
// O(n), but at most once per n shifts.
if (this.head > 1024 && this.head * 2 > this.items.length) {
this.items = this.items.slice(this.head);
this.head = 0;
}
return item;
}
}
head is the index of the front item. shift reads that slot, clears it and moves head forward. No other item moves. Figure 2 traces three pushes and two shifts.
push a, b, c [a] [b] [c]
0 1 2
^ head
shift -> a [-] [b] [c]
0 1 2
^ head
shift -> b [-] [-] [c]
0 1 2
^ head
push d [-] [-] [c] [d]
0 1 2 3
^ head
Figure 2: shift moves head instead of moving the items, so the slots in front of head are empty but still part of the array.
Clearing the slot matters. The garbage collector is the part of Node.js that frees objects nothing refers to anymore. Without this.items[this.head] = undefined, the array would keep a reference to every job it ever handed out, so none of them could be freed.
But don’t the empty slots in front of head pile up forever?
They would, so shift drops them once they are more than half the array. slice(this.head) copies the waiting items into a new array, which is O(n). But it runs only after at least n shifts since the last copy, where n is the number of items it copies.
So each copy of n items comes after at least n cheap shifts, and spread over them, it adds at most one step per shift. That makes shift amortized O(1), for the same reason push is. The head > 1024 part keeps a small queue from copying every few shifts.
The cost is memory. Before a copy, the array can be twice as long as the queue, plus 1,024 slots. Each slot is 8 bytes in Node.js on x64.
A ring buffer: reuse the front
The head index leaves the front of the array empty until the next copy. A ring buffer reuses those slots right away.
A ring buffer is a fixed-size array whose positions wrap around from the last index back to 0. It keeps a head index for the front item and a count of items. Item i of the queue sits at index (head + i) % capacity, where the capacity is the array’s length. So with capacity 4 and head at 2, the first four items sit at indexes 2, 3, 0 and 1.
When the capacity is a power of two, (head + i) & (capacity - 1) gives the same index. This bitwise AND needs no division, because it keeps only the low bits. For example, (2 + 2) & 3 is 0, the same as (2 + 2) % 4.
When the buffer is full, it can’t wrap any further, so it allocates an array twice as large and copies the items into it. Save deque.ts. Its name, and its two methods that take from the back, pop and peekBack, are for a later section:
// A ring buffer: a power-of-two array whose front moves forward and wraps around.
// push, shift, pop and the peeks are O(1); push doubles the buffer when it is full (amortized O(1)).
export class Deque<T> {
private buf: (T | undefined)[];
private head = 0; // index of the front item
private count = 0;
constructor(capacity = 16) {
if (capacity < 1 || (capacity & (capacity - 1)) !== 0) throw new RangeError("capacity must be a power of two");
this.buf = new Array(capacity);
}
get size(): number {
return this.count;
}
// Adds at the back.
push(item: T): void {
if (this.count === this.buf.length) this.grow();
this.buf[(this.head + this.count) & (this.buf.length - 1)] = item;
this.count++;
}
// Removes from the front.
shift(): T | undefined {
if (this.count === 0) return undefined;
const item = this.buf[this.head];
this.buf[this.head] = undefined; // let the garbage collector free it
this.head = (this.head + 1) & (this.buf.length - 1);
this.count--;
return item;
}
// Removes from the back.
pop(): T | undefined {
if (this.count === 0) return undefined;
this.count--;
const i = (this.head + this.count) & (this.buf.length - 1);
const item = this.buf[i];
this.buf[i] = undefined;
return item;
}
peekFront(): T | undefined {
return this.count === 0 ? undefined : this.buf[this.head];
}
peekBack(): T | undefined {
return this.count === 0 ? undefined : this.buf[(this.head + this.count - 1) & (this.buf.length - 1)];
}
// Copies the items in queue order, front first, into an array twice as large.
private grow(): void {
const next: (T | undefined)[] = new Array(this.buf.length * 2);
for (let i = 0; i < this.count; i++) next[i] = this.buf[(this.head + i) & (this.buf.length - 1)];
this.buf = next;
this.head = 0;
}
}
The back of the queue is head + count, wrapped. push writes there, and shift reads at head and moves it one slot forward, wrapping from the last index to 0.
Pause and predict. A Deque with capacity 4 gets push a, b, c, then two shifts, then push d, e, f. Where do e and f land? And when push g finds the buffer full, in what order should grow copy the items?
Figure 3 shows the buffer after each step, as trace-demo.ts prints it.
step buf head count
0 1 2 3
push a, b, c [a] [b] [c] [-] 0 3
shift -> a [-] [b] [c] [-] 1 2
shift -> b [-] [-] [c] [-] 2 1
push d [-] [-] [c] [d] 2 2
push e [e] [-] [c] [d] 2 3 (2 + 2) & 3 = 0
push f [e] [f] [c] [d] 2 4 full
push g [c] [d] [e] [f] [g] [-] [-] [-]
0 1 2 3 4 5 6 7
0 5 grown, copied from head
Figure 3: e and f wrap into the slots that the shifts freed, and grow copies from head in queue order, so the queue stays c, d, e, f, g.
The queue in a full buffer starts at head, not at index 0. That’s why grow reads the items with the same (head + i) & (capacity - 1) formula and writes them to indexes 0, 1, 2, and so on.
shift is O(1). push is O(1) except when it grows. Growing doubles the capacity, so over a run the copies add up to less than 2 per push, and push is amortized O(1).
The capacity is at most twice the largest number of items the queue has held. It never shrinks, which costs memory after a burst. queues.test.ts checks both queues against a plain array over thousands of random operations.
Measure both queues
opening-fast.ts in the lab folder runs the opening’s rounds on both queues, with the same sizes. It fills each queue with makeBacklog and calls bench once per queue. Run node opening-fast.ts:
head-index queue, 100000 rounds
n median ms x prev
10,000 2.82
20,000 2.50 0.9
40,000 1.43 0.6
80,000 3.42 2.4
ring buffer queue, 100000 rounds
n median ms x prev
10,000 2.29
20,000 1.02 0.4
40,000 0.99 1.0
80,000 1.03 1.0
Neither grows with n. The head index stayed between 1.43 and 3.42 ms, and the ring buffer at about 1 ms after the first size. Times this small move around from run to run, so read them as flat, not as a ratio.
At 80,000 waiting jobs, the array took 1409.12 ms. Figure 4 draws the array and the ring buffer at all four sizes.
median ms for 100,000 rounds (each # is about 31 ms)
n = 10,000 array | 7.22
ring | 2.29
n = 20,000 array ####### 228.11
ring | 1.02
n = 40,000 array ################### 597.39
ring | 0.99
n = 80,000 array ############################################# 1409.12
ring | 1.03
Figure 4: the array queue grows with the number of waiting jobs once it passes the cliff, and the ring buffer stays flat, so the gap grows with every doubling.
Rule: Never take items from the front of a large array with
shift(). Move a head index past them, or keep them in a ring buffer.
The next slower request: a monotonic stack
Here is a problem where a stack removes repeated work. You have the response times of requests in the order they arrived. For each request, you want the index of the next request that took longer, or -1 if none did.
The obvious answer scans forward from each request. Here it is, an excerpt from next-slower-bench.ts. The full file in the lab folder also builds the inputs and times both versions.
// For each request, scan forward until a slower one. O(n^2) in the worst case.
export function nextSlowerScan(ms: number[]): number[] {
return ms.map((v, i) => {
for (let j = i + 1; j < ms.length; j++) if (ms[j] > v) return j;
return -1;
});
}
When every request is faster than the one before, no request has an answer, and each scan runs to the end. That’s the scan’s worst case, about n²/2 comparisons, so it’s O(n²).
The repeated work is in the scans that overlap. Keep the requests that are still waiting for an answer, and check each new request against them. A waiting request whose time is lower than a newer waiting request’s would already have been answered by it. So the waiting times never increase from oldest to newest, and the newest waiting request is the one a new time beats first.
A monotonic stack is a stack whose values only decrease (or only increase) from bottom to top. Before you push a new item, you pop every item that would break the order, and the new item is the answer for each item you pop. Save next-slower.ts:
// For each request, the index of the next request that took longer, or -1.
// Monotonic stack: O(n) time, O(n) memory. Each index is pushed once and popped at most once.
export function nextSlower(ms: number[]): number[] {
const result = new Array<number>(ms.length).fill(-1);
const stack: number[] = []; // indexes still waiting; their times never increase from bottom to top
for (let i = 0; i < ms.length; i++) {
while (stack.length > 0 && ms[stack[stack.length - 1]] < ms[i]) {
result[stack.pop()!] = i;
}
stack.push(i);
}
return result;
}
The stack holds indexes, not times, because the answer is an index and the time is one lookup away. Figure 5 traces seven requests, as trace-demo.ts prints them.
ms [120] [80] [95] [300] [90] [90] [150]
0 1 2 3 4 5 6
i ms pops, answer i stack after
0 120 - [0]
1 80 - [0, 1]
2 95 1 [0, 2]
3 300 2, 0 [3]
4 90 - [3, 4]
5 90 - [3, 4, 5] 90 is not slower than 90
6 150 5, 4 [3, 6]
end 3 and 6 stay result [3, 2, 3, -1, 6, 6, -1]
Figure 5: a new time pops every waiting request it beats and answers them, so each index is pushed once and popped at most once.
The while loop can pop many items in one step, as at i = 3. Doesn’t that make it O(n²) again?
It doesn’t, because each index is pushed once and popped at most once over the whole run. So all the pops together are at most n, and nextSlower is O(n) time. The stack can hold all n indexes when times only fall, so it uses O(n) memory.
The comparison is <, because a request that took the same time is not slower. At i = 5, the second 90 does not pop the first. The test file next-slower.test.ts checks that case and compares the stack against the scan on random times.
Pause and predict. On falling times, the scan is O(n²) and the stack O(n). What do you expect on random times?
Run node next-slower-bench.ts:
next slower, scan, falling times
n median ms x prev
10,000 18.27
20,000 71.61 3.9
40,000 286.54 4.0
next slower, monotonic stack, falling times
n median ms x prev
10,000 0.11
20,000 0.28 2.5
40,000 0.62 2.2
next slower, scan, random times
n median ms x prev
10,000 0.23
20,000 0.50 2.2
40,000 1.21 2.4
next slower, monotonic stack, random times
n median ms x prev
10,000 0.19
20,000 0.27 1.4
40,000 0.54 2.0
On falling times, the scan grew 4 times per doubling, as O(n²) predicts. At 40,000 it took 286.54 ms against 0.62 ms for the stack. On random times, the scan grew about 2 times per doubling, and it was only about twice as slow as the stack.
The reason is in the input. With random times, a slower request is usually a few places away, so most scans stop early.
The stack is O(n) for every input, so its value is the guarantee. If your times can arrive in a long falling run, the scan is the one that hurts.
Rule: When each item needs the next (or previous) larger or smaller item, keep the items still waiting for an answer on a monotonic stack.
The maximum of every window: a deque
Module 2 slid a window of k items over an array and kept a running sum. A window is a run of k items next to each other, and sliding it adds one item on the right and drops one on the left. A sum can subtract the item that leaves. A maximum can’t, because when the largest item leaves, you don’t know the next largest.
Suppose you have CPU samples and want the largest value in every window of k consecutive samples. The obvious answer scans each window. Here it is, an excerpt from window-max-bench.ts. The full file also times both versions.
// Scan every window from scratch. O(n * k).
export function windowMaxScan(samples: number[], k: number): number[] {
const out: number[] = [];
for (let i = 0; i + k <= samples.length; i++) {
let max = samples[i];
for (let j = i + 1; j < i + k; j++) if (samples[j] > max) max = samples[j];
out.push(max);
}
return out;
}
There are n − k + 1 windows, and each scan reads k samples, so windowMaxScan is O(n × k).
Most of each scan is repeated work, and the monotonic stack’s idea removes it. Once a newer sample is at least as large as an older one, the older one can never be a window’s maximum again. The newer sample is in every window the older one is still in, and it stays for longer.
So keep only the samples that could still be a maximum, with their values decreasing from oldest to newest. The oldest is then the current maximum.
That list needs two things a stack doesn’t have. New samples push out smaller ones at the newest end, as in the monotonic stack. But the oldest sample also leaves at the other end, when it slides out of the window.
A deque (a double-ended queue, said “deck”) is a sequence you can add to and remove from at both ends. The Deque class above removes from both ends, with shift and pop, and adds at the back. This pattern never adds at the front, so the class leaves that out. Save window-max.ts:
import { Deque } from "./deque.ts";
// The largest value in every window of k consecutive samples.
// A deque of indexes whose values decrease from front to back: O(n) time (each index is pushed
// once and removed at most once), O(k) memory.
export function windowMax(samples: number[], k: number): number[] {
if (k < 1) throw new RangeError("k must be at least 1");
const out: number[] = [];
const dq = new Deque<number>(); // indexes; their values decrease from front to back
for (let i = 0; i < samples.length; i++) {
while (dq.size > 0 && samples[dq.peekBack()!] <= samples[i]) dq.pop();
dq.push(i);
if (dq.peekFront()! <= i - k) dq.shift(); // the front index left the window
if (i >= k - 1) out.push(samples[dq.peekFront()!]);
}
return out;
}
Each step pops every index at the back whose value is at most the new sample, then pushes the new index. If the front index is k or more places behind, it has left the window, so the step shifts it off. The window covers indexes i - k + 1 to i, so the front leaves when it is at most i - k.
Figure 6 traces windowMax([30, 10, 50, 20, 20, 40, 10], 3), as trace-demo.ts prints it.
samples [30] [10] [50] [20] [20] [40] [10] k = 3
0 1 2 3 4 5 6
i value pop back shift front deque after max
0 30 - - [0] -
1 10 - - [0, 1] -
2 50 1, 0 - [2] 50
3 20 - - [2, 3] 50
4 20 3 - [2, 4] 50
5 40 4 2, left [5] 40
6 10 - - [5, 6] 40
Figure 6: the deque keeps only the samples that could still be a maximum, largest at the front, so the front is always the window’s maximum.
At i = 4, the new 20 pops the older 20, because <= keeps only the newer of two equal values, which stays in the window longer. At i = 5, index 2 is 3 places behind, so it leaves even though 50 is still the largest value seen.
Every index is pushed once and removed at most once, by pop or by shift, so windowMax is O(n) time. The deque never holds more than k + 1 indexes, so its memory is O(k).
Measure both, for n and for k
The first two tables keep k at 1,000 and double n. The last two keep 200,000 samples and make k 10 times larger at each step.
Pause and predict. As k goes from 10 to 10,000, what happens to each version’s time?
Run node window-max-bench.ts:
window max k = 1,000, scan
n median ms x prev
100,000 55.15
200,000 111.57 2.0
400,000 222.41 2.0
window max k = 1,000, deque
n median ms x prev
100,000 5.91
200,000 6.85 1.2
400,000 14.24 2.1
window max, 200,000 samples, scan (n = k)
n median ms x prev
10 3.54
100 18.52 5.2
1,000 109.25 5.9
10,000 972.81 8.9
window max, 200,000 samples, deque (n = k)
n median ms x prev
10 6.27
100 6.81 1.1
1,000 6.37 0.9
10,000 6.03 0.9
With k fixed, both grew about 2 times when n doubled, because both are linear in n. The 1.2 in the deque’s first step comes from times too small to read a ratio from. The difference is the factor k, and the k sweep shows it, drawn in Figure 7.
median ms for 200,000 samples (each # is about 22 ms)
k = 10 scan | 3.54
deque | 6.27
k = 100 scan # 18.52
deque | 6.81
k = 1,000 scan ##### 109.25
deque | 6.37
k = 10,000 scan ############################################# 972.81
deque | 6.03
Figure 7: the scan grows with k and the deque doesn’t, so the deque wins by more as the window grows, and loses only for tiny windows.
The deque stayed at about 6 ms for every k. The scan grew 5.2, 5.9, then 8.9 times per 10 times more k.
At k = 10, the scan won, 3.54 ms against 6.27 ms. For a window that small, a plain loop is faster and has less code to get right. The deque pays off once k reaches the hundreds.
Rule: For the maximum of every window, keep a deque of indexes in decreasing order. Pop smaller values at the back, and shift the front when it leaves.
Three more shapes of these patterns
The monotonic stack and deque come in a few more shapes. Each has a sign in the problem that points to it. The lab’s variations.ts holds two of them, previousLarger and windowMin. Run node variations.ts:
previousLarger([50, 30, 40, 60, 20]): [ -1, 0, 0, -1, 3 ]
windowMin([30, 10, 50, 20, 20, 40, 10], 3): [ 10, 10, 20, 20, 10 ]
Look back instead of forward
Here is previousLarger, an excerpt from variations.ts:
// For each item, the index of the last earlier item that is larger, or -1.
// The same stack as nextSlower, but the answer is read from the top after popping.
// O(n) time, O(n) memory.
export function previousLarger(values: number[]): number[] {
const result: number[] = [];
const stack: number[] = []; // indexes; their values decrease from bottom to top
for (let i = 0; i < values.length; i++) {
while (stack.length > 0 && values[stack[stack.length - 1]] <= values[i]) stack.pop();
result.push(stack.length === 0 ? -1 : stack[stack.length - 1]);
stack.push(i);
}
return result;
}
nextSlower answers an item when it is popped. previousLarger answers the new item after the pops. Whatever is left on top is larger than it, and it’s the closest such item to the left. So the same stack answers “the last earlier item that is larger”.
In [50, 30, 40, 60, 20], the 40 pops the 30 and finds 50 on top, so its answer is index 0. The 60 pops everything and finds an empty stack, so its answer is -1.
The items between the previous larger index p and i are all at most the item at i. So the run of such items ending at i is i − p items long. The sign is “the last earlier item that is larger”, or “how many in a row before this one were at most this one”. Exercise 4 uses it.
Flip the comparison for smaller values
To get the next smaller item, or the minimum of every window, flip the comparison. windowMin pops while the back is >= the new sample, so the deque’s values increase from front to back and the front is the minimum. On Figure 6’s samples with k = 3, it returns [ 10, 10, 20, 20, 10 ]. The sign is the same as before with “smaller”, “cheapest” or “minimum” in it.
A window that grows and shrinks
Module 2 also had a window with no fixed size, where right adds an item and left moves forward while the window breaks a rule. A deque works there too. The only change is when the front leaves. It is out of the window once its index is less than left.
The sign is “the longest run such that the largest and smallest differ by at most…”. Exercise 5 uses it with two deques, one for the maximum and one for the minimum.
Underneath: what each array method costs in V8
This section explains why an array makes a good stack and a poor queue. Each fact holds as of V8 14.6.202.34, the version in Node.js 26.13.1.
push: It writes into spare room at the end, or grows the array’s memory and copies, as Module 1 showed. Amortized O(1).pop: It reads the last element and lowers the length. No other element moves, so it’s O(1). On an empty array, it returnsundefinedand changes nothing.shift: On an array past the cliff, it moves every element one slot left, so it’s O(n). Below about 15,000 elements, V8 can usually move the array’s start instead. That’s why the opening’s queue was fast at 10,000.unshift: It always moves every element one slot right, or copies them all into a larger block. V8 has no trick for adding at the front, sounshiftis O(n) at every size.
So the end of an array is cheap to change and the front is not. The rules for shift and pop did not change between V8 12.4 (Node.js 22) and V8 14.6 (Node.js 26). JavaScript still has no built-in queue or deque. TC39, the committee that designs JavaScript, has no proposal for one on its list of proposals.
Underneath: which queue to use
This table puts the queues of this module next to the linked-list queue from Module 4:
| Queue | Cost per operation | Memory | Choose it when |
|---|---|---|---|
Array with push and shift |
O(1) up to about 15,000 items, O(n) above | 8 bytes per slot | the queue can never pass a few thousand items |
Head index (IndexQueue) |
amortized O(1) | 8 bytes per slot, up to twice the items before a copy | you want the least code that is O(1) at any size |
Ring buffer (Deque) |
O(1), push amortized |
8 bytes per slot, capacity up to twice the largest size, never shrinks | you also need the back, or the size stays steady |
| Linked list (Module 4) | O(1) | 40 bytes per node | you also remove items from the middle |
Common mistakes
mistakes.ts writes six bugs that are easy to make with stacks and queues, and prints what each one returns. Run node mistakes.ts:
1. queue drained with pop(): [ 'third', 'second', 'first' ]
2. queue after a naive grow: [ 'c', 'd', undefined, undefined ] (want [ 'c', 'd', 'e', 'f' ])
3. spans closed, with request never ended: 1 (want an error)
4. next slower of [50, 50, 60]: [ 1, 2, -1 ] (want [ 2, 2, -1 ])
5. window max of [9, 1, 2, 3], k = 2: [ 9, 9, 9 ] (want [ 9, 2, 3 ])
6. array length with 10 jobs waiting, after 1,000,000 rounds: 1,000,010
Using pop for a queue. pop takes the newest item, so the jobs run last in, first out. A queue takes from the front with a head index, with Deque.shift, or with shift() on a short array.
Growing a ring buffer by copying the array as it is. The full buffer [e, f, c, d] with head = 2 holds c, d, e, f. Copied to the same positions in a buffer of 8, e and f stay at 0 and 1. But the queue now continues at 4 and 5, which are empty. Copy in queue order from head, and set head to 0, as grow does.
Not checking the stack at the end. A stack that is not empty after the loop holds items that never closed. spansBad returns without checking, so a request that never ended passes. Check open.length after the loop.
<= where the problem says “larger”. With <=, the second 50 pops the first. So the first 50 gets index 1 as its “next slower” request, which took the same time. Use < when equal values don’t count, and check equal values in the tests.
Never shifting the front out of the window. Without the shift, the 9 stays at the front long after its window has passed, and every later window reports it. Shift the front when its index is at most i - k.
A head index that never drops the used front. The queue holds 10 jobs, but the array grew to 1,000,010 slots, 8 MB of empty slots. Copy the waiting items to a new array once the used front is over half, as IndexQueue does, or use a ring buffer.
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 23 tests fail until you write the five answers. Exercises 2 to 5 each end with a test that times a large input, so an answer that is correct but too slow fails. The slow folder holds such answers.
Exercise 1: simplify a file path (easy)
Write simplifyPath(path) for an absolute file path. . means the current folder, .. the parent folder, and the parent of the root is the root. Empty parts from // are dropped.
The result starts with / and has no / at the end, except the root itself. Start from exercises/simplify-path.ts:
// Exercise 1: simplify an absolute file path. "." means this folder, ".." the parent folder
// (the root's parent is the root), and empty parts from "//" are dropped. Return a path that
// starts with "/" and has no "/" at the end, except the root itself, "/".
export function simplifyPath(path: string): string {
throw new Error("not implemented");
}
The tests check these cases:
.and..- empty parts
- going above the root
- names such as
...that only look like dots - a path with 100,000 folder names and 99,999
..parts
Hint
Split the path on /. Which part pushes a folder name on a stack, and which one pops? What should pop() do when the stack is empty?
Solution
// Exercise 1: simplify an absolute file path. "." means this folder, ".." the parent folder
// (the root's parent is the root), and empty parts from "//" are dropped. Return a path that
// starts with "/" and has no "/" at the end, except the root itself, "/".
// A stack of folder names: O(n) time and memory for a path of n characters.
export function simplifyPath(path: string): string {
const folders: string[] = [];
for (const part of path.split("/")) {
if (part === "" || part === ".") continue;
if (part === "..") folders.pop(); // pop() of an empty stack does nothing and returns undefined
else folders.push(part);
}
return "/" + folders.join("/");
}
Cost: O(n) time for a path of n characters, because split, the loop and join each read it once. O(n) memory for the parts. Going above the root needs no special case, because pop() on an empty array changes nothing.
Exercise 2: requests in the last few seconds (easy)
A rate limiter needs the number of requests in a sliding time window. Write RecentRequests, whose hit(t) records a request at time t and returns how many requests fall in (t - windowMs, t].
Times never decrease. Each hit must be amortized O(1), without shift(). Start from exercises/recent-requests.ts:
// Exercise 2: hit(t) records a request at time t (times never decrease) and returns
// how many requests fall in the last windowMs milliseconds: times in (t - windowMs, t].
// Each hit must be amortized O(1). Do not use shift().
export class RecentRequests {
constructor(windowMs: number) {
throw new Error("not implemented");
}
hit(t: number): number {
throw new Error("not implemented");
}
}
The tests check these cases:
- the window’s edges
- several requests at the same time
- 300,000 requests in a window of 50,000 ms, in under 500 ms
Hint
The times form a queue. Each one enters when it is hit and leaves when it gets too old. Use a head index, as IndexQueue does. When does the head move, and why does it never move back?
Solution
// Exercise 2: hit(t) records a request at time t (times never decrease) and returns
// how many requests fall in the last windowMs milliseconds: times in (t - windowMs, t].
// Each hit must be amortized O(1). Do not use shift().
// A queue of times with a head index: each time enters once and leaves once, so hit() is
// amortized O(1). Memory: O(w) for w requests in the window, up to about 2w before compaction.
export class RecentRequests {
private times: number[] = [];
private head = 0; // index of the oldest time still in the window
private windowMs: number;
constructor(windowMs: number) {
this.windowMs = windowMs;
}
hit(t: number): number {
this.times.push(t);
while (this.times[this.head] <= t - this.windowMs) this.head++;
if (this.head > 1024 && this.head * 2 > this.times.length) {
this.times = this.times.slice(this.head);
this.head = 0;
}
return this.times.length - this.head;
}
}
Cost: one hit can move head many times, but each time enters once and leaves once, so hit is amortized O(1). Memory is O(w) for w requests in the window, up to about twice that before the copy. The while loop stops at the new time at the latest, because t is never older than the window.
With shift() in place of the head index, the window of 50,000 times is above the cliff, and the last test took 2,039 ms.
Exercise 3: keep the last N log lines (medium)
Write LogTail, which keeps the last capacity log lines. When it is full, push overwrites the oldest line. toArray() returns the lines oldest first.
The capacity can be any number from 1 up, not only a power of two. Start from exercises/log-tail.ts:
// Exercise 3: keep the last `capacity` log lines. When it is full, push overwrites the oldest line.
// toArray() returns the lines oldest first. Throw a RangeError when capacity < 1.
// Target: push O(1), toArray O(capacity), memory O(capacity).
export class LogTail {
constructor(capacity: number) {
throw new Error("not implemented");
}
get size(): number {
throw new Error("not implemented");
}
push(line: string): void {
throw new Error("not implemented");
}
toArray(): string[] {
throw new Error("not implemented");
}
}
The tests check these cases:
- a tail that is not yet full
- overwriting
- capacity 1 and 0
- random runs against
slice(-capacity), for capacities 2, 5, 7 and 100 - 300,000 lines into a tail of 50,000, timed
Hint
Use a ring buffer with a head and a count, and % instead of &, because the capacity is not a power of two. A full buffer never grows here. Which slot does a push overwrite, and where does head go next?
Solution
// Exercise 3: keep the last `capacity` log lines. When it is full, push overwrites the oldest line.
// toArray() returns the lines oldest first. Throw a RangeError when capacity < 1.
// A ring buffer of fixed size: push O(1), toArray O(capacity), memory O(capacity).
export class LogTail {
private lines: string[];
private head = 0; // index of the oldest line
private count = 0;
constructor(capacity: number) {
if (capacity < 1) throw new RangeError("capacity must be at least 1");
this.lines = new Array(capacity);
}
get size(): number {
return this.count;
}
push(line: string): void {
const cap = this.lines.length;
if (this.count < cap) {
this.lines[(this.head + this.count) % cap] = line;
this.count++;
} else {
this.lines[this.head] = line; // overwrite the oldest, which is now the newest
this.head = (this.head + 1) % cap;
}
}
toArray(): string[] {
const out: string[] = [];
for (let i = 0; i < this.count; i++) out.push(this.lines[(this.head + i) % this.lines.length]);
return out;
}
}
Cost: push is O(1), one write and at most one index move. toArray is O(capacity). Memory is O(capacity) and never grows. When the buffer is full, the oldest line is at head, so the new line goes into that slot and head moves to the next oldest.
Exercise 4: days at most this bad (medium)
For each day’s error count, return how many days in a row, ending that day, had a count at most that day’s count. The day itself counts, so every answer is at least 1. For [100, 80, 60, 70, 60, 75, 85] the answer is [1, 1, 1, 2, 1, 4, 6]. Start from exercises/days-at-most.ts:
// Exercise 4: for each day, how many days in a row, ending that day, had an error count
// at most that day's count. The day itself counts, so every answer is at least 1. O(n).
export function daysAtMost(counts: number[]): number[] {
throw new Error("not implemented");
}
The tests check these cases:
- the example
- equal counts
- rising and falling counts
- random counts against a slow version
- 50,000 rising counts, in under 100 ms
Hint
The run ending at day i stops at the previous day with a larger count. Find it with previousLarger from the variations section. What is the answer when there is no such day?
Solution
// Exercise 4: for each day, how many days in a row, ending that day, had an error count
// at most that day's count. The day itself counts, so every answer is at least 1.
// Monotonic stack of earlier days whose counts are larger than every later day so far:
// O(n) time (each day is pushed once and popped at most once), O(n) memory.
export function daysAtMost(counts: number[]): number[] {
const result: number[] = [];
const stack: number[] = []; // indexes; their counts decrease from bottom to top
for (let i = 0; i < counts.length; i++) {
while (stack.length > 0 && counts[stack[stack.length - 1]] <= counts[i]) stack.pop();
// The top is now the previous larger day, or there is none.
result.push(stack.length === 0 ? i + 1 : i - stack[stack.length - 1]);
stack.push(i);
}
return result;
}
Cost: O(n) time, because each day is pushed once and popped at most once. O(n) memory for the stack when counts only fall. The <= pops equal counts, because a day with the same count is “at most” this one and belongs to the run.
A scan back from each day is O(n²) on rising counts, and it took 889 ms on the last test.
Exercise 5: the longest steady stretch (harder)
Write longestSteady(samples, limit): the length of the longest run of consecutive samples whose largest and smallest values differ by at most limit, or 0 for no samples. It must be O(n). Start from exercises/longest-steady.ts:
// Exercise 5: the length of the longest run of consecutive samples whose largest and smallest
// values differ by at most `limit`. Return 0 for no samples. O(n).
// You may import the Deque from "../deque.ts".
export function longestSteady(samples: number[], limit: number): number {
throw new Error("not implemented");
}
The tests check these cases:
- an example
limit = 0- an empty input and one sample
- random inputs against a slow version
- 50,000 samples that are all one steady run, timed
Hint
Use the window that grows and shrinks from Module 2, with left and right. Keep one deque for the window’s maximum, as in windowMax, and one for its minimum, as in windowMin. When the window breaks the limit, move left forward. When does each front index leave?
Solution
// Exercise 5: the length of the longest run of consecutive samples whose largest and smallest
// values differ by at most `limit`. Return 0 for no samples.
// A window that grows and shrinks (Module 2), with two monotonic deques of indexes:
// one for the window's maximum, one for its minimum. Each index enters and leaves each deque
// at most once, and `left` only moves forward: O(n) time, O(n) memory in the worst case.
import { Deque } from "../deque.ts";
export function longestSteady(samples: number[], limit: number): number {
const maxQ = new Deque<number>(); // values decrease from front to back
const minQ = new Deque<number>(); // values increase from front to back
let left = 0;
let best = 0;
for (let right = 0; right < samples.length; right++) {
const v = samples[right];
while (maxQ.size > 0 && samples[maxQ.peekBack()!] <= v) maxQ.pop();
maxQ.push(right);
while (minQ.size > 0 && samples[minQ.peekBack()!] >= v) minQ.pop();
minQ.push(right);
// Shrink from the left until the window is steady again.
while (samples[maxQ.peekFront()!] - samples[minQ.peekFront()!] > limit) {
left++;
if (maxQ.peekFront()! < left) maxQ.shift();
if (minQ.peekFront()! < left) minQ.shift();
}
best = Math.max(best, right - left + 1);
}
return best;
}
Cost: O(n) time. right and left each move at most n times, and each index enters and leaves each deque at most once. Memory is O(n) in the worst case, when the whole input is one steady run. The shrinking loop always stops, because a window of one sample has a difference of 0.
Moving left is safe for the reason Module 2 gave. Adding a sample can only widen the difference, and dropping one can only narrow it. Growing a window from every start is O(n²), and on the last test it took 4,743 ms.
Going deeper
You can skip this section. It covers the V8 details and the Node.js queue that the main path left out. The facts hold as of V8 14.6.202.34, the version in Node.js 26.13.1.
Where the shift cliff sits
An array’s backing store is the block of memory that holds its elements. To left-trim a store is to move its start one slot forward, so the first element drops off and nothing is copied. V8’s large-object space is where it keeps objects over 128 KB, and a store there can’t be left-trimmed (CanMoveObjectStart in heap.cc).
So shift left-trims while the array has more than 100 elements and its store is not in large-object space. Otherwise it moves every element, as Module 1 drew (RemoveElement in elements.cc). A store passes 128 KB at about 16,000 slots.
For an array built with push, the step comes earlier, when the length passes 15,044. That’s because the store grows from 15,044 slots to 22,583 at that push (NewElementsCapacity in js-objects.h). The opening benchmark on Node.js 22.17 showed the same cliff between 10,000 and 20,000 jobs.
What push, pop and at() do underneath
push grows a full store to old + old/2 + 16 slots. pop writes a hole in the last slot and lowers the length (ArrayPrototypePop in builtins-array-gen.cc).
When the length falls well under the capacity (2 × length + 16 ≤ capacity), V8 shrinks the store in place. V8 calls this right-trimming. So a stack that grew large gives memory back as it empties (DecreaseLength in elements.cc).
Array.prototype.at came in ECMAScript 2022, so stack.at(-1) reads the top without stack[stack.length - 1]. It has been supported since Chrome 92, as the V8 feature page says.
The queue inside Node.js
Node.js has its own queue for process.nextTick callbacks, FixedQueue in lib/internal/fixed_queue.js. It is a singly linked list of ring buffers with 2,048 slots each. When the newest buffer is full, it links a new one instead of copying the queue. An empty buffer at the front is unlinked and kept for reuse.
That design combines the two structures. Growing costs no copy, and memory goes back as buffers empty, which a single Deque never does. Its cost is more code.
Cheat sheet
Figure 8 maps each sign in a problem to the structure that fits it.
sign in the problem structure cost
nesting, undo, "most recent open first" stack (push, pop) O(1) each
first in, first out, can grow large head index or ring O(1) amortized
keep only the last N items fixed-size ring O(1) each
next or previous larger (or smaller) monotonic stack O(n) total
max or min of every window of k deque of indexes O(n) total
longest run with max - min <= limit two deques, left/right O(n) total
Figure 8: a stack serves the newest item and a queue the oldest, and the monotonic versions drop every item that can no longer be an answer.
- Stack:
push,popandat(-1)on an array, all O(1) (pushamortized). The last item in is the first out. - Queue: never
shift()a large array, because past about 15,000 items each call moves them all. Use a head index (amortized O(1), up to 2× memory) or a ring buffer (O(1), never shrinks). - Ring buffer: item i at
(head + i) & (capacity - 1); grow by copying fromheadin queue order. - Monotonic stack: pop every item the new one beats, and the new one is each popped item’s answer. Each item is pushed once and popped at most once, so O(n) total.
- Window maximum: a deque of indexes in decreasing order; pop at the back, shift the front when it leaves. O(n) time, O(k) memory.
- Simple can win: the scan beat the deque at k = 10, and the next-slower scan was close to O(n) on random times.
- Next: Module 6 uses a stack and a queue to walk trees, and shows how deep recursion can go in Node.js before it crashes.
Sources
- V8 source at 14.6.202.34, the version in Node.js 26.13.1:
elements.cc(RemoveElement,DecreaseLength,AddArguments),builtins-array-gen.cc(ArrayPrototypePop),heap.cc(CanMoveObjectStart),js-objects.h(NewElementsCapacity),js-array.h(kMaxCopyElements). - V8: at method for relative indexing (2021).
- Node.js 26.13.1 source:
lib/internal/fixed_queue.jsandlib/internal/process/task_queues.js. - ECMAScript specification:
Array.prototype.pop,Array.prototype.shift,Array.prototype.at; TC39 proposals.