Data Structures and Algorithms, Pattern by Pattern / Module 01

Module 1: Measuring Cost Before You Code

Name the time and memory cost of code before you run it, measure it with a small benchmark script, and read input limits to know the cost you need.

Suppose you have the user IDs from a day of requests, and you want each ID once, in the order it first appeared. Here are two correct functions that do it. Save them as dedupe.ts:

// Two correct ways to remove duplicates from a list, keeping the first copy of each value.

// For each item, scan everything kept so far: O(n * k) time, k = distinct values; O(n^2) when all differ.
export function dedupeSlow<T>(items: T[]): T[] {
  const kept: T[] = [];
  for (const item of items) {
    if (!kept.includes(item)) kept.push(item);
  }
  return kept;
}

// A Set answers "seen before?" in O(1) on average: O(n) time, O(k) extra memory.
export function dedupeFast<T>(items: T[]): T[] {
  return [...new Set(items)];
}

Both return the same list. But in one run on 2,000,000 random IDs, dedupeFast took 0.26 seconds and dedupeSlow took 237 seconds, almost four minutes.

This module teaches you to see that difference before you run anything, and to check it with numbers when you do. It also sets up the tools every later module uses.

After this module, you can:

  • run a TypeScript file with Node.js 26 and time a function at several input sizes with bench.ts
  • state the time and memory cost of a function in Big O, and check it against a benchmark table
  • name the cost of common array, Set and Map operations, and spot a slow call hidden inside a loop
  • explain why push() is cheap on average, even though one push can copy the whole array
  • read an input limit and turn it into the cost your solution needs

Run TypeScript files with Node.js 26

The course uses Node.js 26.13.1 and no packages. Node.js 26 is a long-term-support (LTS) release: a version that gets bug and security fixes for years, not months. Make a folder for the module, and tell Node.js that its files are ES modules (files that use import and export):

mkdir module-01 && cd module-01 && echo '{ "type": "module" }' > package.json

Save dedupe.ts from above into the folder. You’ll run it in the next section with node measure-dedupe.ts, with no build step and no flag. The course’s code, with the exercises and their solutions, lives at github.com/vespaiach/data-structure-algorithms.

How can Node.js run TypeScript with no build step? It uses type stripping: it replaces every type annotation with spaces and runs what is left as JavaScript. So it does not check your types. Run tsc --noEmit in your editor or CI if you want type checks.

Stripping only works for TypeScript syntax that disappears without leaving code behind. These features would need Node.js to write new JavaScript, so they fail:

  • enum declarations (use a union of string literals or an as const object)
  • namespace blocks that contain runtime code
  • parameter properties, such as constructor(private x: number)
  • import aliases, such as import x = require("x")
  • decorators

Two more rules come from the same design. Imports must name the real file, import { bench } from "./bench.ts", because Node.js does not guess extensions. And a type-only import needs the type keyword (import type { Item } from "./item.ts"), or it fails at run time.

Type stripping has run without a flag since Node.js 23.6.0 and 22.18.0 (2025), according to the Node.js TypeScript docs. “Going deeper” covers older versions.

Measure both functions at several sizes

One timing tells you little. You need the time at several input sizes, and how much it grows from one size to the next. Save this script as bench.ts. Every later module reuses it unchanged:

// bench.ts: run a function on inputs of several sizes and print a table of times.
// For each size: one warm-up run, then `runs` timed runs on fresh inputs.
// Prints the median time and how many times slower it is than the previous size.

export function bench<T>(
  label: string,
  sizes: number[],
  makeInput: (n: number) => T,
  fn: (input: T) => unknown,
  runs = 5,
): void {
  console.log(`\n${label}`);
  console.log("n".padStart(14) + "median ms".padStart(12) + "x prev".padStart(9));
  let prev = 0;
  for (const n of sizes) {
    fn(makeInput(n)); // warm-up: lets the JIT compile fn before we time it
    const times: number[] = [];
    for (let r = 0; r < runs; r++) {
      const input = makeInput(n); // building the input is not timed
      const start = performance.now();
      fn(input);
      times.push(performance.now() - start);
    }
    times.sort((a, b) => a - b);
    const median = times[Math.floor(times.length / 2)];
    const ratio = prev ? (median / prev).toFixed(1) : "";
    console.log(n.toLocaleString("en-US").padStart(14) + median.toFixed(2).padStart(12) + ratio.padStart(9));
    prev = median;
  }
}

Notice three choices in it:

  • A warm-up run. V8, the JavaScript engine inside Node.js, first interprets a function, then compiles the parts that run often into machine code. A compiler that works while the program runs is a JIT compiler (“just in time”). The warm-up gives it a chance to compile fn before the timed runs.
  • A fresh input for every run. A function that changes its input, such as sort(), would get an easier input on its second run. Building the input is not timed.
  • The median, and the ratio to the previous size. The median is the middle time after sorting the runs, so one or two slow runs do not move it. The x prev column shows how the time grows.

Now save measure-dedupe.ts. It builds n random user IDs between 0 and n - 1, so about 63% of them are distinct:

import { bench } from "./bench.ts";
import { dedupeSlow, dedupeFast } from "./dedupe.ts";

// n user IDs drawn from 0..n-1, so about 63% of them are distinct.
const userIds = (n: number): number[] => Array.from({ length: n }, () => Math.floor(Math.random() * n));

bench("dedupeSlow", [10_000, 20_000, 40_000, 80_000], userIds, dedupeSlow);
bench("dedupeFast", [10_000, 20_000, 40_000, 80_000], userIds, dedupeFast);
bench("dedupeFast, larger", [100_000, 1_000_000, 10_000_000], userIds, dedupeFast);

Pause and predict. Each size is twice the one before. When n doubles, how many times longer will dedupeSlow take? And dedupeFast?

Run node measure-dedupe.ts:

dedupeSlow
             n   median ms   x prev
        10,000        4.02
        20,000       15.18      3.8
        40,000       61.38      4.0
        80,000      256.05      4.2

dedupeFast
             n   median ms   x prev
        10,000        0.30
        20,000        0.92      3.0
        40,000        1.63      1.8
        80,000        3.08      1.9

dedupeFast, larger
             n   median ms   x prev
       100,000        4.63
     1,000,000       75.43     16.3
    10,000,000     1892.69     25.1

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.

Doubling n makes dedupeSlow about 4 times slower and dedupeFast about 2 times slower. Ignore the first row of each table, because very short runs are the ones most affected by noise. Figure 1 draws the first two tables to scale.

median ms at each n (each # is about 5 ms)

n = 10,000   slow #                                                  4.02
             fast |                                                  0.30
n = 20,000   slow ###                                               15.18
             fast |                                                  0.92
n = 40,000   slow ############                                      61.38
             fast |                                                  1.63
n = 80,000   slow ################################################## 256.05
             fast |                                                  3.08

Figure 1: each doubling of n multiplies the slow version by about 4 and the fast one by about 2, so the gap keeps widening.

At 80,000 IDs the gap is 83 times. At 2,000,000 IDs it is about 900 times. To see that yourself, the lab’s one-large-run.ts times each function once: node one-large-run.ts 2000000. Expect the slow half to take minutes.

Note: bench.ts is a teaching tool. It shows growth between sizes well, but it is not a precise timer. “Going deeper” lists what it misses.

Count steps to predict the growth

Why 4 and 2? Count the steps each function does on a tiny input, [3, 1, 3, 2, 1]. Here a step is one small piece of work, such as one comparison.

dedupeSlow compares each item with the kept items until it finds a match or reaches the end. Figure 2 traces it.

items   [3] [1] [3] [2] [1]
         0   1   2   3   4

step  item  kept before   compared with   result
  1    3    []            (nothing)       push -> kept [3]
  2    1    [3]           3               push -> kept [3, 1]
  3    3    [3, 1]        3               found, skip
  4    2    [3, 1]        3, 1            push -> kept [3, 1, 2]
  5    1    [3, 1, 2]     3, 1            found, skip
                          6 comparisons in total

Figure 2: dedupeSlow compares each item with the kept list, and that list grows as it runs.

Call the number of items n. If every item is distinct, the kept list grows by one each step, so the comparisons are 0 + 1 + 2 + … + (n – 1). That sum is n(n – 1) / 2. For 80,000 IDs it is about 3.2 billion comparisons.

You don’t need the exact sum to predict the growth. Big O is a short way to write how the number of steps grows as n grows. To get it, keep only the fastest-growing part of the formula, and drop any constant number in front of it. So n(n – 1) / 2 = n²/2 – n/2 becomes O(n²), read “order n squared”.

In other words, O(n²) tells you that doubling the input makes the work about 4 times larger, whatever the exact formula was.

The random IDs are about 63% distinct, so the kept list ends at about 0.63 n items, not n. That is smaller by a constant factor, so the cost is still O(n²). The worst case is the input that makes a function slowest. For dedupeSlow, it is a list with no duplicates.

Rule: Count the steps as a formula in n, keep the fastest-growing part, and drop the constant. That part predicts the x prev column.

Why the Set version grows linearly

dedupeFast passes the items to new Set(items). A Set is a hash table: it turns each value into a number, called a hash, and uses that number to find the place where the value is stored. So checking “is 3 already here?” goes straight to one place, without looking at the other values. Figure 3 traces the same input.

step  item  already in the Set?   Set after
  1    3    no                    {3}
  2    1    no                    {3, 1}
  3    3    yes, not added        {3, 1}
  4    2    no                    {3, 1, 2}
  5    1    yes, not added        {3, 1, 2}
then [...set] copies the 3 values out: [3, 1, 2]

Figure 3: dedupeFast does one Set step per item, however many values the Set already holds.

That is n Set steps plus a copy of the kept values, so dedupeFast is O(n). A Set also returns its values in the order they were first added. So the result keeps the first copy of each ID, the same as dedupeSlow.

Is a Set step always that fast? A Set step is O(1), constant time, in the average case: the expected cost over typical inputs. In the worst case, many values land in the same place in the table, and a lookup slows down. Module 3 shows how that happens.

Cost classes and what doubling does

These are the cost classes the course uses, with what each does to the time when n doubles. In the table, log n is the number of times you can halve n before you reach 1. For example, log₂ 1,024 is 10.

Cost Name When n doubles, the time Example
O(1) constant stays the same Set.has, pop()
O(log n) logarithmic grows by one step binary search (Module 9)
O(n) linear doubles includes, dedupeFast
O(n log n) “n log n” a bit more than doubles sort()
O(n²) quadratic grows 4 times dedupeSlow
O(2^n) exponential is squared listing all subsets (Module 10)

Now look at the “larger” rows of the dedupeFast table. With 10 times more IDs, the time grew 16.3 times, then 25.1 times, not 10 times. The number of steps does grow 10 times, but each step gets slower once the data no longer fits in the CPU’s fast memory. Big O counts steps, not the time each step takes, and “Going deeper” has the details.

Memory has a cost too

Both functions also use extra memory: memory they allocate beyond their input. dedupeSlow allocates the kept list and dedupeFast the Set. Big O describes memory the same way, so both use O(k) extra memory, where k is the number of distinct values. But a Set stores more per value than an array. Save memory.ts:

// How much heap one million numbers take in an array, a Set and a Map.
// Run with: node --expose-gc memory.ts
const gc = (globalThis as { gc?: () => void }).gc;
if (!gc) throw new Error("run with node --expose-gc");

function heapMB(make: () => unknown): string {
  gc();
  const before = process.memoryUsage().heapUsed;
  const kept = make();
  gc();
  const after = process.memoryUsage().heapUsed;
  if (!kept) throw new Error("unreachable"); // keeps `kept` alive until here
  return ((after - before) / 1024 / 1024).toFixed(1) + " MB";
}

const n = 1_000_000;
const ids = Array.from({ length: n }, (_, i) => i);
console.log("array of 1,000,000 small integers ", heapMB(() => Array.from({ length: n }, (_, i) => i)));
console.log("array of 1,000,000 doubles        ", heapMB(() => Array.from({ length: n }, (_, i) => i + 0.5)));
console.log("Set of 1,000,000 small integers   ", heapMB(() => new Set(ids)));
console.log("Map of 1,000,000 small integers   ", heapMB(() => new Map(ids.map((i) => [i, i]))));

The heap is the memory where JavaScript keeps objects. The garbage collector frees the parts of it that nothing uses anymore. The --expose-gc flag gives the script a gc() function, so it can run the garbage collector before and after each measurement. Run node --expose-gc memory.ts:

array of 1,000,000 small integers  7.6 MB
array of 1,000,000 doubles         7.6 MB
Set of 1,000,000 small integers    20.0 MB
Map of 1,000,000 small integers    28.0 MB

Figure 4 shows what each slot holds.

bytes per slot (1 word = 8 bytes in Node.js 26 on x64)

array  [value]                                  8 bytes
Set    [key][link] + half of a [hash entry]    20 bytes
Map    [key][value][link] + half [hash entry]  28 bytes

Set and Map round their capacity up to a power of two:
1,000,000 keys -> 1,048,576 slots -> 20 MiB for the Set, 28 MiB for the Map

Figure 4: a Set costs 2.5 words per slot and a Map 3.5, against 1 word per array element.

An array stores each number in one 8-byte slot. A Set slot holds the key plus a link used when two keys hash to the same place, and the table adds more on top. So the Set in dedupeFast costs about 2.6 times the memory of the input array. That is the price of its speed.

What common operations cost

dedupeSlow hides its cost inside one method call. kept.includes(item) looks like one step, but it scans the array. To write the cost of a function, you need the cost of each operation it calls.

This script measures ten common ones. Each row does 1,000 operations on a collection of n items, so an O(1) operation gives a flat column and an O(n) operation grows about 10 times per row. Save operation-costs.ts:

// The cost of common array, Set and Map operations, measured at three sizes.
// Each function does 1,000 operations on a collection of n items, so the time
// stays flat for O(1) operations and grows about 10x per row for O(n) ones.
// Loops that only read return a count or a sum, so the compiler cannot remove the work.
import { bench } from "./bench.ts";

const sizes = [10_000, 100_000, 1_000_000];
const numbers = (n: number): number[] => Array.from({ length: n }, (_, i) => i);
const OPS = 1_000;

bench("push 1,000 items", sizes, numbers, (a) => {
  for (let i = 0; i < OPS; i++) a.push(i);
});
bench("pop 1,000 items", sizes, numbers, (a) => {
  let sum = 0;
  for (let i = 0; i < OPS; i++) sum += a.pop()!;
  return sum;
});
bench("includes() on a missing value, 1,000 times", sizes, numbers, (a) => {
  let found = 0;
  for (let i = 0; i < OPS; i++) if (a.includes(-1 - i)) found++;
  return found;
});
bench("Set.has() on a missing value, 1,000 times", sizes, (n) => new Set(numbers(n)), (s) => {
  let found = 0;
  for (let i = 0; i < OPS; i++) if (s.has(-1 - i)) found++;
  return found;
});
bench("Map.get() on a present key, 1,000 times", sizes, (n) => new Map(numbers(n).map((i) => [i, i])), (m) => {
  let sum = 0;
  for (let i = 0; i < OPS; i++) sum += m.get(i)!;
  return sum;
});
bench("unshift 1,000 items", sizes, numbers, (a) => {
  for (let i = 0; i < OPS; i++) a.unshift(i);
});
bench("splice() one item out of the middle, 1,000 times", sizes, numbers, (a) => {
  for (let i = 0; i < OPS; i++) a.splice(a.length >> 1, 1);
});
bench("shift 1,000 items", sizes, numbers, (a) => {
  for (let i = 0; i < OPS; i++) a.shift();
});
bench("copy with [...a], once", sizes, numbers, (a) => [...a]);
bench("sort() a shuffled array with (x, y) => x - y, once", sizes,
  (n) => numbers(n).map(() => Math.random()),
  (a) => a.sort((x, y) => x - y));

Pause and predict. Which rows stay flat as n grows from 10,000 to 1,000,000, and which grow about 10 times per row?

Run node operation-costs.ts:

push 1,000 items
             n   median ms   x prev
        10,000        0.24
       100,000        0.20      0.8
     1,000,000        5.65     28.3

pop 1,000 items
             n   median ms   x prev
        10,000        0.00
       100,000        0.00      0.7
     1,000,000        0.00      1.5

includes() on a missing value, 1,000 times
             n   median ms   x prev
        10,000        1.27
       100,000       13.96     11.0
     1,000,000      225.10     16.1

Set.has() on a missing value, 1,000 times
             n   median ms   x prev
        10,000        0.02
       100,000        0.03      1.3
     1,000,000        0.08      3.1

Map.get() on a present key, 1,000 times
             n   median ms   x prev
        10,000        0.03
       100,000        0.04      1.4
     1,000,000        0.11      2.9

unshift 1,000 items
             n   median ms   x prev
        10,000        1.57
       100,000       20.01     12.8
     1,000,000      238.52     11.9

splice() one item out of the middle, 1,000 times
             n   median ms   x prev
        10,000        0.74
       100,000        8.19     11.1
     1,000,000       88.98     10.9

shift 1,000 items
             n   median ms   x prev
        10,000        0.04
       100,000       17.13    386.3
     1,000,000      238.03     13.9

copy with [...a], once
             n   median ms   x prev
        10,000        0.01
       100,000        0.04      8.6
     1,000,000        4.24     94.3

sort() a shuffled array with (x, y) => x - y, once
             n   median ms   x prev
        10,000        2.41
       100,000       39.33     16.4
     1,000,000      524.74     13.3

Read each row by its x prev column:

Operation Cost per call Why
push, pop O(1) (push on most calls, next section) they work at the end of the array
includes, indexOf O(n) they scan until they find the value
Set.has, Map.get O(1) on average a hash lookup
unshift O(n) it moves every element one place right
splice in the middle O(n) it moves every element after the gap
shift treat as O(n) see the 10,000 row, and “Underneath”
[...a], slice, concat O(n) they copy every element
sort O(n log n) TimSort, see “Underneath”

The smallest rows are the least reliable, because a few microseconds is close to what the timer can measure. That’s why the pop row prints 0.00 and the [...a] row jumps 8.6 and then 94.3 times. Read those rows with the cost table, not on their own.

The shift row jumps 386 times between 10,000 and 100,000 items. At 10,000 items V8 removes the first element without moving the others, and at 100,000 it moves all of them. For your cost estimates, treat shift() as O(n).

Why one push can copy the whole array

Look again at the push row. Pushing 1,000 items onto an array of 1,000,000 took 5.65 ms, and onto 100,000 it took 0.20 ms. If every push were O(1), the row would be flat.

An array keeps its elements in a separate block of memory called its backing store, which can be larger than the array’s length. Array.from({ length: n }) makes a backing store with no free slot. So the first of the 1,000 pushes must allocate a larger store and copy all n elements into it, which is O(n).

The other 999 pushes write into free slots. V8 grows the store by half plus 16 slots. Figure 5 starts from a full array of 4.

before: length 4, capacity 4, no free slot
  [a][b][c][d]
   0  1  2  3

push(e): new capacity = 4 + (4 >> 1) + 16 = 22
  copy a, b, c, d into the new store, then write e
  [a][b][c][d][e][ ][ ][ ] ... [ ]
   0  1  2  3  4  5  6  7       21

the next 17 pushes write into free slots and copy nothing

Figure 5: one push copies every element, and it buys room for many cheap pushes.

So how much does a push cost? The amortized cost of an operation is its total cost over a long run of calls, divided by the number of calls. With V8’s growth rule, n pushes onto an empty array copy at most about 3n items in total. That is 3 copies per push, a constant, so push is amortized O(1).

In other words, the rare push that copies everything is paid for by the many cheap pushes after it. But that only works because each growth adds room in proportion to the size. all = all.concat(post.tags) in a loop builds a new array on every pass and copies everything collected so far. That is 1 + 2 + … + n copies, O(n²) in total, and Exercise 2 starts from that code.

Rule: A cost that is paid rarely, and buys room in proportion to the size, spreads to O(1) per call. A cost paid on every call does not.

Turn an input limit into a target cost

Before you write a solution, the size of the input tells you which cost you can afford. You need one number for that: how many steps the machine does per second. Save steps-per-second.ts:

// Roughly how many simple loop steps this machine does per second.
import { bench } from "./bench.ts";

bench("sum of 0..n-1 in a plain loop", [10_000_000, 100_000_000, 1_000_000_000], (n) => n, (n) => {
  let sum = 0;
  for (let i = 0; i < n; i++) sum += i;
  return sum;
}, 3);

Run node steps-per-second.ts:

sum of 0..n-1 in a plain loop
             n   median ms   x prev
    10,000,000       40.62
   100,000,000      155.39      3.8
 1,000,000,000     1057.91      6.8

A billion additions took about one second, so one loop step costs about 1 ns. The smaller runs were slower per step, so read the largest row.

But real steps do more than add two numbers. They read properties, hash keys and create objects. In the dedupeFast table, each ID cost 46 to 189 ns, about 50 to 190 loop steps. So this course uses a budget of about 10⁸ (100 million) simple steps per second.

To read a limit, find the largest n whose step count fits in the budget, for each cost class. Exercise 4 asks you to write that function. Its output, for a budget of 10⁸ steps, gives Figure 6.

largest n for 10^8 steps     the cost you can afford
             26              O(2^n)
            464              O(n^3)
         10,000              O(n^2)
      4,523,071              O(n log n)
    100,000,000              O(n)

Figure 6: read the table from the input limit to the slowest cost that still fits in about a second.

Suppose a job gets a log of up to 1,000,000 lines. O(n²) would be 10¹² steps, about three hours at 10⁸ per second, so you need O(n log n) or better. If the limit is 5,000, an O(n²) solution with 2.5 × 10⁷ steps is fine, and it may be simpler to write. So the limit also tells you when the simple solution is good enough.

Three places a hidden cost hides

The slow code in this module is not a hard algorithm problem. It is an O(n) operation inside a loop over n items. It comes in three common shapes.

A scan inside a loop. dedupeSlow calls includes once per item, so O(n) per call times n calls gives O(n²). Every O(n) method in the table above does the same inside a loop. The sign is a method call on the whole collection, inside a loop over a collection. The fix is usually a Set or Map built once before the loop:

// excerpt: before, O(orders x customers)
for (const order of orders) {
  const customer = customers.find((c) => c.id === order.customerId);
}
// after, O(orders + customers): build the Map once
const byId = new Map(customers.map((c) => [c.id, c]));
for (const order of orders) {
  const customer = byId.get(order.customerId);
}

A copy inside a loop. all = all.concat(x) and all = [...all, x] each copy the whole array on every pass, so the loop is O(n²). The sign is an assignment that rebuilds the variable it reads. Use push on one array instead.

A sort inside a loop. Sorting a list to take its largest item costs O(n log n), and doing it on every pass of a loop costs O(n² log n). The sign is sort() followed by [0] or .at(-1). One pass with a running maximum is O(n), and Module 8 shows what to use when you need the top 10.

Underneath: arrays, Sets and sort in V8

This section explains the measurements above with V8’s source. The V8 version is 14.6.202.34, the one in Node.js 26.13.1, and engine details can change in later versions.

Array growth. The growth rule in Figure 5 is JSObject::NewElementsCapacity in V8’s js-objects.h.

shift. Up to about 16,000 elements, V8 can drop the first element by moving the start of the backing store, which is O(1). Above that, it moves every element, so Module 5 builds a queue that does not depend on shift.

Set and Map. V8 stores both in an ordered hash table, which keeps entries in the order they were added. That is why dedupeFast keeps the first copy of each ID in its original order. The table is in V8’s ordered-hash-table.h.

sort. Since V8 7.0 (2018), sort uses TimSort, as the V8 blog post Getting things sorted in V8 explains. TimSort is O(n log n) in the worst case and O(n) on input that is already sorted. It is also a stable sort: items that compare equal keep their original order.

Since ES2019, the language spec requires sort to be stable, as tc39/ecma262 PR #1340 shows. So if you sort orders by date and then by customer, each customer’s orders stay in date order.

When the choice flips. A Set is not always the better choice:

  • For a few dozen items, a scan with includes is as fast as a Set and allocates nothing. Use the Set when the input can grow.
  • If memory is tight and you don’t need the original order, sort the array in place and drop each item equal to the one before it. That is O(n log n) time with no extra structure, and Module 3 compares the two with numbers.
  • If the output must be sorted anyway, the sort does the dedupe for almost nothing extra.

Common mistakes

Trusting a test’s timeout for slow synchronous code. node:test accepts { timeout: 2000 }, but a timeout cannot stop code that never pauses to let other work run. In one run, a test with { timeout: 200 } whose body ran for 2 seconds passed. The Node.js test runner docs say the timeout “is not a reliable mechanism for canceling tests”. So the exercise tests time themselves with performance.now() and assert.ok(ms < limit).

Sorting numbers without a comparator. A comparator is the function you pass to sort to say which of two items comes first. Predict the output of this line, then run it with node -p:

[10, 9, 1, 100].sort()
[ 1, 10, 100, 9 ]

With no comparator, sort() converts each value to a string and compares the strings. Pass (x, y) => x - y for numbers.

Reading one size only. At 10,000 IDs, 0.30 ms against 4.02 ms looks like “13 times faster”. But the gap widens with every doubling, and at 2,000,000 IDs it is about 900 times.

Timing the input with the function, or reusing an input. If makeInput runs inside the timed part, you measure the input builder. If a second sort run gets the array the first run already sorted, TimSort finishes in O(n). That’s why bench.ts builds a fresh input outside the timer.

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"

The tests for the three unwritten functions fail until you write them. collect-tags.ts starts correct but slow, so only its timing test fails. Each test that checks speed times the function itself and fails with a message such as took 2830 ms.

Exercise 1: two email lists (easy)

Two marketing lists each hold thousands of email addresses. Write hasCommon(a, b), which returns true if the lists share at least one address, in O(a + b) time. Start from exercises/has-common.ts:

// Do two lists of emails share at least one address?
// Target: O(a + b) time.
export function hasCommon(a: string[], b: string[]): boolean {
  throw new Error("not implemented");
}

The test checks small cases and that two lists of 10,000 addresses take under 500 ms. When it passes, measure a nested-scan version against yours with bench.ts at 2,000, 4,000 and 8,000 addresses. Then check that the growth matches the cost you expect.

Hint

A loop over b that calls a.includes(email) is O(a × b). Which structure answers “is this address in a?” without scanning a?

Solution
// Do two lists of emails share at least one address?
// O(a + b) time: one pass to fill the Set, one pass of O(1) lookups. O(a) extra memory.
export function hasCommon(a: string[], b: string[]): boolean {
  const seen = new Set(a);
  return b.some((email) => seen.has(email));
}

Cost: O(a + b) time on average, O(a) extra memory for the Set. some stops at the first shared address.

solutions/measure-has-common.ts measures both versions:

// Measure the nested scan against the Set version: node solutions/measure-has-common.ts
import { bench } from "../bench.ts";
import { hasCommon } from "./has-common.ts";

// The first version most people write: O(a x b) string comparisons.
function hasCommonSlow(a: string[], b: string[]): boolean {
  return b.some((email) => a.includes(email));
}

// Two lists with no shared address, so both versions do all their work.
// padStart gives every address the same length, so every comparison reads the characters.
const lists = (n: number): [string[], string[]] => [
  Array.from({ length: n }, (_, i) => `user${String(i).padStart(6, "0")}@a.io`),
  Array.from({ length: n }, (_, i) => `user${String(i).padStart(6, "0")}@b.io`),
];

const sizes = [2_000, 4_000, 8_000];
bench("hasCommonSlow", sizes, lists, ([a, b]) => hasCommonSlow(a, b));
bench("hasCommon with a Set", sizes, lists, ([a, b]) => hasCommon(a, b));
hasCommonSlow
             n   median ms   x prev
         2,000       96.66
         4,000      384.97      4.0
         8,000     1544.61      4.0

hasCommon with a Set
             n   median ms   x prev
         2,000        0.52
         4,000        1.10      2.1
         8,000        2.24      2.0

The nested scan grows 4 times per doubling, so it is O(a × b), which is O(n²) for two lists of n. The Set version grows 2 times, O(n).

The script gives every address the same length, because V8’s String::SlowEquals compares the lengths of two strings first. Without the padding, the slow version skips more comparisons, and its ratios drift above 4.

Exercise 2: collect every tag (easy)

exercises/collect-tags.ts is correct but slow. Find the hidden cost and make it O(total tags):

// Collect every tag of every post into one list, in order.
// This version is correct but slow. Find the hidden cost and make it O(total tags).
export function collectTags(posts: { tags: string[] }[]): string[] {
  let all: string[] = [];
  for (const post of posts) {
    all = all.concat(post.tags);
  }
  return all;
}

As given, it passes the correctness tests and fails the timing test:

✖ 20,000 posts with 3 tags each take under 500 ms (2830.026746ms)
Hint

How many elements does concat copy on the last pass of the loop? And on the one before?

Solution
// Collect every tag of every post into one list, in order.
// concat() copied the whole list on every post: O(posts x total tags).
// push() appends in amortized O(1): O(total tags) time, O(total tags) memory for the result.
export function collectTags(posts: { tags: string[] }[]): string[] {
  const all: string[] = [];
  for (const post of posts) {
    for (const tag of post.tags) all.push(tag);
  }
  return all;
}

Cost: O(T) time and O(T) memory for the result, where T is the total number of tags. posts.flatMap((post) => post.tags) has the same cost in one line.

Exercise 3: a growable array (medium)

Write the growth rule of a backing store yourself. GrowableArray keeps its items in a fixed-size array. When it is full, push allocates storage twice as large and copies every item, and copies counts the items copied. Start from exercises/growable-array.ts:

// A list on top of fixed-size storage, like the backing store of a JavaScript array.
// When the storage is full, push() allocates storage twice as large and copies every item.
// `copies` counts the items copied so far.
export class GrowableArray<T> {
  copies = 0;

  get length(): number {
    throw new Error("not implemented");
  }

  get capacity(): number {
    throw new Error("not implemented");
  }

  push(item: T): void {
    throw new Error("not implemented");
  }

  get(index: number): T {
    throw new Error("not implemented");
  }
}

The tests check three things:

  • the capacity goes 1, 2, 4, 8
  • get throws a RangeError outside the list
  • n pushes copy fewer than 2n items
Hint

Start with capacity 1. When the store doubles from c to 2c, the push copies c items. Add up the copies for n = 8: 1 + 2 + 4.

Solution
// A list on top of fixed-size storage, like the backing store of a JavaScript array.
// When the storage is full, push() allocates storage twice as large and copies every item.
// One push costs O(n) when it grows, but n pushes copy fewer than 2n items in total:
// amortized O(1) per push. Memory: at most 2n slots.
export class GrowableArray<T> {
  copies = 0;
  #items: (T | undefined)[] = new Array(1);
  #length = 0;

  get length(): number {
    return this.#length;
  }

  get capacity(): number {
    return this.#items.length;
  }

  push(item: T): void {
    if (this.#length === this.#items.length) {
      const bigger: (T | undefined)[] = new Array(this.#items.length * 2);
      for (let i = 0; i < this.#length; i++) {
        bigger[i] = this.#items[i];
        this.copies++;
      }
      this.#items = bigger;
    }
    this.#items[this.#length++] = item;
  }

  get(index: number): T {
    if (index < 0 || index >= this.#length) throw new RangeError(`index ${index} out of range`);
    return this.#items[index] as T;
  }
}

Cost: push is O(n) on the calls that grow and amortized O(1) overall. The copies are 1 + 2 + 4 + … up to n, which is less than 2n. get is O(1), and memory is at most 2n slots.

Doubling copies fewer items than V8’s rule (under 2n, against about 3n), but it leaves more room unused. Right after a growth, half of the store is empty, against about a third with V8’s rule.

Exercise 4: read the input limit (medium)

Write largestInput(steps, budget): the largest n for which steps(n) is at most budget, or 0 if even n = 1 does not fit. steps is one of the cost functions in exercises/largest-input.ts:

// Reading input limits: the largest n whose step count fits in a budget.
// steps(n) is how many basic steps an algorithm takes on an input of size n.
export const costs = {
  "n": (n: number) => n,
  "n log n": (n: number) => n * Math.log2(n),
  "n^2": (n: number) => n * n,
  "n^3": (n: number) => n * n * n,
  "2^n": (n: number) => 2 ** n,
};

export function largestInput(steps: (n: number) => number, budget: number): number {
  throw new Error("not implemented");
}

For a budget of 10⁸, the tests expect 100,000,000 for n, 10,000 for n², 464 for n³ and 26 for 2ⁿ. Counting up from 1 would take 10⁸ calls for the linear case, so find a faster way.

Hint

Every cost function grows as n grows. Double n while it still fits, then search between the last n that fit and twice that.

Solution
// Reading input limits: the largest n whose step count fits in a budget.
// steps(n) is how many basic steps an algorithm takes on an input of size n.
export const costs = {
  "n": (n: number) => n,
  "n log n": (n: number) => n * Math.log2(n),
  "n^2": (n: number) => n * n,
  "n^3": (n: number) => n * n * n,
  "2^n": (n: number) => 2 ** n,
};

// Double n until it no longer fits, then walk back up one by one from the last fit.
// O(log N + N/2) calls in the worst case, N = the answer; fine for a table of limits.
export function largestInput(steps: (n: number) => number, budget: number): number {
  let n = 1;
  if (steps(n) > budget) return 0;
  while (steps(n * 2) <= budget) n *= 2;
  while (steps(n + 1) <= budget) n++;
  return n;
}

// Print the table: node largest-input.ts
if (process.argv[1] === import.meta.filename) {
  for (const [name, steps] of Object.entries(costs)) {
    console.log(name.padEnd(8), largestInput(steps, 1e8).toLocaleString("en-US"));
  }
}

node solutions/largest-input.ts prints the table behind Figure 6:

n        100,000,000
n log n  4,523,071
n^2      10,000
n^3      464
2^n      26

Cost: the doubling loop makes O(log N) calls, where N is the answer. The walk from the last power of two can take up to N/2 more calls, so the whole function is O(N) calls in the worst case. For n = 10⁸, the doubling stops at 2²⁶ = 67,108,864, and the walk takes about 33 million calls. That is a fraction of a second, and Module 9 shows how halving the gap makes the walk O(log N).

Going deeper

You can skip this section. It covers details the main path left out.

What bench.ts misses

  • One warm-up may not be enough for V8 to fully optimize a function, so the first size can look slower per item than later ones.
  • A garbage-collection pause lands inside whichever run triggers it.
  • Anything under about a microsecond prints as 0.00.
  • The compiler can remove work whose result nobody reads. So every function you measure should return its result, as the scripts in this course do.

A serious benchmark tool repeats each measurement until the numbers are stable and reports their spread. It also controls garbage collection between samples and keeps every result alive.

Type stripping on older Node.js versions

Type stripping arrived behind a flag in Node.js 22.6.0. It became stable in v25.2.0 and v24.12.0. Node.js 26.0.0 removed the older --experimental-transform-types flag, which could run enums. The Node.js TypeScript docs list each change.

On Node.js 22.6 to 22.17, add the flag to every command in this course: node --experimental-strip-types file.ts. Node.js 26 still accepts that flag, so the same command works on both. On Node.js 22.17 and older without the flag, or with --no-strip-types, Node.js reads the file as plain JavaScript. It stops at the first annotation (the file path and stack trace are cut):

const n: number = 1;
      ^

SyntaxError: Missing initializer in const declaration

Why the larger rows grew faster than n

A Set of 100,000 numbers takes about 2.5 MB and fits in this CPU’s 12 MB L3 cache, a small, fast memory next to the CPU. A Set of 1,000,000 numbers takes 20 MB and does not. Once the table is larger than the cache, most lookups wait for main memory. We did not measure cache misses, but the sizes fit that explanation.

The sort row shows the same effect. It grows 16.4 and 13.3 times per 10 times more items, while n log n predicts about 12.5 times at these sizes, because log₂ 100,000 / log₂ 10,000 = 1.25. The extra most likely comes from the cache, and the class is still O(n log n).

What each slot holds

The numbers from memory.ts match V8’s source to the byte. Node.js 26 on x64 is built without pointer compression, so each slot takes 8 bytes. Small integers sit in the slot itself, and an array of only doubles stores them unboxed, also in 8 bytes.

A Set slot holds the key and a link to the next key that hashed to the same place. The table that maps hashes to slots adds one more word for every two slots. The capacity doubles when the table is full, which is amortized O(1) per insert for the same reason as push.

How shift picks O(1) or O(n)

V8 can remove the first element without moving the others. It left-trims the backing store: it moves the start of the block one slot forward and frees the old first slot. It does this only when the array has more than 100 elements and the heap allows it to move the start of that object.

The heap refuses for objects in large-object space, which holds every object over 128 KB. At 8 bytes per slot, that is an array of about 16,000 elements. The code is FastElementsAccessor::RemoveElement in V8’s elements.cc. The builtin that calls it is in V8’s array-shift.tq.

Figure 7 shows both paths.

array of 101 to about 16,000 elements: left-trim, O(1)
  [a][b][c][d][e]      shift()      [-][b][c][d][e]
   ^ start                              ^ start moves one slot, [-] is freed

array over 128 KB (large-object space): move, O(n)
  [a][b][c][d][e]      shift()      [b][c][d][e][ ]
   ^ start                           ^ start stays, 4 elements move

Figure 7: shift() is O(1) only while V8 may move the start of the backing store, which it may not for large arrays.

More engine details

  • Where the 3n comes from. The last growth of an array copies at most n items, the one before it about 2n/3, then 4n/9, and so on. That sum stays under 3n.
  • includes on numbers. V8 searches arrays of small integers and doubles with SIMD instructions, which compare several elements per instruction. That makes each step cheaper but keeps O(n), as V8’s simd.cc shows.
  • What the spec promises. The ECMAScript spec asks Map and Set only for access times “sublinear on the number of elements” on average, as its Map objects section says.
  • A hard size limit. In Node.js 26.13.1, inserting integers into a Map or a Set stops at 16,777,216 entries (2²⁴) with RangeError: Map maximum size exceeded.

Cheat sheet

Figure 8 is the summary of the module: the cost classes and what each does when the input doubles.

cost         n x 2 makes the time   seen in this module
O(1)         x 1                    Set.has, Map.get, pop, push (amortized)
O(log n)     + 1 step               (binary search, Module 9)
O(n)         x 2                    includes, [...a], dedupeFast
O(n log n)   a bit over x 2         sort
O(n^2)       x 4                    dedupeSlow, concat in a loop
O(2^n)       squared                (all subsets, Module 10)

Figure 8: the x prev column of a benchmark tells you which row your code is in.

  • Cost: count steps as a formula in n, keep the fastest-growing part, drop constants.
  • Check: run bench.ts at two or three sizes and read x prev: about 2 per doubling is O(n), 4 is O(n²).
  • O(1): push (amortized), pop, Set.has, Map.get, index access.
  • O(n): includes, indexOf, find, splice, unshift, shift, concat, [...a].
  • O(n log n): sort(), which is stable; pass a comparator for numbers.
  • Hidden cost: a scan, a copy or a sort inside a loop over the same data turns O(n) into O(n²) or worse.
  • Budget: about 10⁸ simple steps per second; n = 10,000 allows O(n²), n = 10⁶ needs O(n log n).
  • Memory: a Set buys its speed with memory, 20 bytes per number against 8 in an array.

Next, Module 2 finds the busiest minute in a request log without re-scanning the log for every minute, using two pointers, sliding windows and prefix sums.

Sources