Suppose a checkout service receives a list of orders, and a retry can submit the same order twice. This correct function returns the ID of the first order whose ID already appeared earlier in the list. Save it as duplicates.ts:
// Has any order been submitted twice? Return the ID of the first order whose ID
// already appeared earlier in the list, or undefined.
export type Order = { id: string; customer: string; amount: number };
// Compare each order with every earlier order: O(n^2) time, O(1) extra memory.
export function firstDuplicateSlow(orders: Order[]): string | undefined {
for (let i = 0; i < orders.length; i++) {
for (let j = 0; j < i; j++) {
if (orders[j].id === orders[i].id) return orders[i].id;
}
}
return undefined;
}
In one run on 200,000 orders with no repeated ID, firstDuplicateSlow took 138 seconds, more than two minutes. The version you’ll write in this module took 0.073 seconds on the same list.
The inner loop asks one question, “did this ID appear before?”, and answers it by reading every earlier order. This module answers it with one lookup in a hash table. That’s a structure that turns each key into a number and uses the number to go straight to the key’s place. JavaScript’s Map and Set are hash tables.
After this module, you can:
- replace a scan over earlier items with a
SetorMaplookup, and say what that costs in time and memory - explain how a hash table finds, adds and deletes a key, and when a lookup stops being O(1)
- pick the hashing shape a problem needs: checking existence, counting, grouping, or looking up an earlier running total
- choose between a
Map, a plain object and sorting for a job, and say why
Measure the scan over earlier orders
Make a folder for the module, as in Module 1, and copy bench.ts into it unchanged:
mkdir module-03 && cd module-03 && echo '{ "type": "module" }' > package.json
Then save measure-duplicates.ts. It builds n orders with random 10-character IDs, so in practice no ID repeats. That’s the worst case, because every function must look at every order. Two of the three functions don’t exist yet, so read the first table now, and run the script yourself after the section on sorting.
import { bench } from "./bench.ts";
import { firstDuplicateSlow, firstDuplicate, hasDuplicateBySorting, type Order } from "./duplicates.ts";
// n orders with random 10-character IDs: no duplicates in practice, the worst case.
const orders = (n: number): Order[] =>
Array.from({ length: n }, () => ({ id: Math.random().toString(36).slice(2, 12), customer: "c1", amount: 10 }));
bench("firstDuplicateSlow", [5_000, 10_000, 20_000], orders, firstDuplicateSlow);
bench("firstDuplicate (Set)", [5_000, 10_000, 20_000], orders, firstDuplicate);
bench("hasDuplicateBySorting", [5_000, 10_000, 20_000], orders, hasDuplicateBySorting);
bench("firstDuplicate (Set), larger", [100_000, 1_000_000], orders, firstDuplicate);
bench("hasDuplicateBySorting, larger", [100_000, 1_000_000], orders, hasDuplicateBySorting);
Pause and predict. firstDuplicateSlow compares order i with the i orders before it. When the list doubles, how many times longer does it take?
Here is the first table that node measure-duplicates.ts printed:
firstDuplicateSlow
n median ms x prev
5,000 88.99
10,000 357.79 4.0
20,000 1449.19 4.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.
Each doubling makes it about 4 times slower, so firstDuplicateSlow is O(n²). The inner loop runs 0 + 1 + … + (n − 1) times in total, about n²/2 comparisons. At 200,000 orders that is 2 × 10¹⁰ comparisons, 200 times the budget of about 10⁸ steps per second from Module 1.
How a hash table finds a key without reading the others
To see why one lookup is enough, look inside a small hash table. toy-hash-set.ts, in the module’s folder, stores strings only, and it is laid out the way V8 lays out Map and Set. Here is an excerpt with the parts a lookup uses:
// A toy hash function: the same string always gives the same number.
export function toyHash(key: string): number {
let h = 0;
for (let i = 0; i < key.length; i++) h = (h * 31 + key.charCodeAt(i)) >>> 0;
return h;
}
export class ToyHashSet {
buckets: number[] = [-1, -1];
keys: (string | undefined)[] = []; // undefined marks a deleted entry
chain: number[] = [];
size = 0;
bucketOf(key: string): number {
return toyHash(key) & (this.buckets.length - 1); // the bucket count is a power of 2
}
indexOf(key: string): number {
for (let i = this.buckets[this.bucketOf(key)]; i !== -1; i = this.chain[i]) {
if (this.keys[i] === key) return i;
}
return -1;
}
has(key: string): boolean {
return this.indexOf(key) !== -1;
}
// ...
}
A hash function turns a key into a number, and it must give the same number for equal keys. toyHash multiplies its running result by 31 and adds each character code. >>> 0 keeps the result a 32-bit integer that is never negative.
A bucket is one slot of the buckets array. A key belongs to bucket hash & (buckets.length - 1), which is the hash modulo the bucket count, because that count is a power of 2. So with 2 buckets, an even hash goes to bucket 0 and an odd hash to bucket 1.
keys holds the entries in the order you added them. Each bucket holds the index of its newest entry, or -1 for none. A chain is the path through the entries of one bucket: chain[i] is the next entry after entry i, and -1 ends it.
hash-table-demo.ts adds four order IDs to an empty set and prints the table after each step. Here is the first part of what node hash-table-demo.ts prints:
toyHash("a7") = 3062, bucket 0 of 2
toyHash("o2") = 3491, bucket 1 of 2
toyHash("c9") = 3126, bucket 0 of 2
toyHash("x1") = 3769, bucket 1 of 2
after a7, o2, c9, x1 (2 buckets, 4 entries: full)
buckets [2,3]
entry 0: a7, chain -> -1
entry 1: o2, chain -> -1
entry 2: c9, chain -> 0
entry 3: x1, chain -> 1
Figure 1 draws the table after the four adds.
buckets [2] [3]
0 1
entries [a7] [o2] [c9] [x1]
0 1 2 3
chain -1 -1 0 1
bucket 0: [c9] -> [a7]
bucket 1: [x1] -> [o2]
Figure 1: the entries sit in insertion order, and each bucket is a short chain through them, newest first.
What a lookup does when keys share a bucket
In Figure 1, a7 and c9 both landed in bucket 0. How does has tell them apart?
Two different keys in the same bucket are a collision. A lookup walks the chain of the key’s bucket and compares the key with each entry on it, using ===. It never looks at the other buckets.
Pause and predict. toyHash("b2") is 3088, and b2 is not in the set. Which keys does has("b2") compare it with, and how many?
The demo prints the keys each lookup compares:
has("a7"): bucket 0, compares entry 2 (c9), entry 0 (a7) -> true
has("b2"): bucket 0, compares entry 2 (c9), entry 0 (a7) -> false
Figure 2 traces both lookups.
has("a7") toyHash 3062, bucket 3062 & 1 = 0
bucket 0 -> [c9] not a7 -> [a7] equal true
has("b2") toyHash 3088, bucket 3088 & 1 = 0
bucket 0 -> [c9] not b2 -> [a7] not b2 -> -1 end false
Figure 2: a lookup compares only the keys in one bucket, never the whole set.
So a lookup costs one pass over the key’s characters to hash it, plus one comparison per key in its bucket. If the keys spread evenly, a bucket holds only a few keys, however large the set is. That makes a lookup O(1) on average. If every key lands in the same bucket, a lookup reads them all, which is O(n), the scan you started with.
Rule: A hash lookup is O(1) on average because it reads one bucket. It becomes O(n) when many keys share that bucket.
How the table stays fast as it grows
With a fixed number of buckets, the chains would grow as you add keys. So the table watches its load factor, the number of entries it allows per bucket. ToyHashSet allows 2, as V8 does, so 2 buckets hold at most 4 entries.
When the table is full, add calls rehash first. To rehash is to build a table with more buckets and add every live key to it again. Every key must be placed again, because its bucket depends on the bucket count. Here are add and rehash, excerpted from toy-hash-set.ts:
export class ToyHashSet {
// ...
add(key: string): this {
if (this.has(key)) return this;
// Load factor 2, as in V8: room for 2 entries per bucket, holes included.
if (this.keys.length === 2 * this.buckets.length) this.rehash(2 * this.buckets.length);
const b = this.bucketOf(key);
this.keys.push(key);
this.chain.push(this.buckets[b]); // the new entry points to the old head of its bucket
this.buckets[b] = this.keys.length - 1;
this.size++;
return this;
}
// ...
// Build a new table with `bucketCount` buckets and add the live keys again, in order.
rehash(bucketCount: number): void {
const live = this.keys.filter((k) => k !== undefined);
this.buckets = new Array<number>(bucketCount).fill(-1);
this.keys = [];
this.chain = [];
this.size = 0;
for (const key of live) this.add(key);
}
// ...
}
add doubles the bucket count when the table is full. Then it puts the new entry at the head of its bucket’s chain. The fifth ID, o3, finds the table full, and the demo prints:
after o3 (the table was full, so it rehashed to 4 buckets first)
buckets [4,3,2,1]
entry 0: a7, chain -> -1
entry 1: o2, chain -> -1
entry 2: c9, chain -> 0
entry 3: x1, chain -> -1
entry 4: o3, chain -> -1
a7: bucket 2 of 4
o2: bucket 3 of 4
c9: bucket 2 of 4
x1: bucket 1 of 4
o3: bucket 0 of 4
Figure 3 shows the buckets before and after.
before: 2 buckets, 4 entries (full) after: 4 buckets, 5 entries
bucket 0: [c9] -> [a7] bucket 0: [o3]
bucket 1: [x1] -> [o2] bucket 1: [x1]
bucket 2: [c9] -> [a7]
bucket 3: [o2]
Figure 3: doubling the bucket count spreads the keys out again, so the chains stay short.
One rehash costs O(n), but it doubles the room, so the next n adds need no rehash. That makes adding a key amortized O(1): an occasional add is slow, but the average cost per add stays constant. Module 1 made the same argument for push.
delete doesn’t move any entry, because other chains may pass through it. It sets the key to undefined, which marks the entry as deleted, and the next rehash drops it. In the demo, delete("o2") leaves entry 1: (deleted), and the set iterates as [ 'a7', 'c9', 'x1', 'o3' ].
toy-hash-set.test.ts checks the toy against a real Set over 5,000 random adds and deletes, including the iteration order. Run it with node --test toy-hash-set.test.ts.
Remember the IDs you’ve seen in a Set
Back to the orders. Instead of reading every earlier order, keep the IDs you’ve seen in a Set and ask it. Add firstDuplicate to duplicates.ts:
// Remember every ID seen so far in a Set: O(n) average time, O(n) extra memory.
export function firstDuplicate(orders: Order[]): string | undefined {
const seen = new Set<string>();
for (const order of orders) {
if (seen.has(order.id)) return order.id;
seen.add(order.id);
}
return undefined;
}
seen.has and seen.add are O(1) on average, and the loop runs once per order, so firstDuplicate is O(n) average time. It keeps up to n IDs, so it needs O(n) extra memory, where the slow version needed O(1). Here are the next tables from the same run:
firstDuplicate (Set)
n median ms x prev
5,000 0.98
10,000 3.12 3.2
20,000 6.47 2.1
firstDuplicate (Set), larger
n median ms x prev
100,000 40.78
1,000,000 656.15 16.1
From 10,000 to 20,000 orders the time doubles, as O(n) predicts. The first step, at under a millisecond, is noisy. At 20,000 orders firstDuplicate takes 6.47 ms against 1,449.19 ms, about 220 times less. Figure 4 draws both at the same three sizes.
median ms at each n (each # is about 29 ms)
n = 5,000 slow ### 88.99
Set | 0.98
n = 10,000 slow ############ 357.79
Set | 3.12
n = 20,000 slow ################################################## 1449.19
Set | 6.47
Figure 4: the scan grows 4 times per doubling and the Set about 2 times, so the gap doubles with every doubling.
Why did the Set version grow 16.1 times from 100,000 to 1,000,000 orders, and not 10?
Module 1 saw the same jump with a Set of numbers. It came once the table was larger than the CPU’s 12 MB cache, the small, fast memory next to the processor. bench.ts can’t show what the cache does, so read it as O(n) with a larger cost per step at large sizes.
Rule: When a loop asks “have I seen this before?”, keep what you’ve seen in a
Set. You pay O(n) memory for a lookup that doesn’t scan.
duplicates.test.ts checks all three functions. Run it with node --test duplicates.test.ts.
Three more shapes of hashing
Checking existence is one shape. Three more come up often, and each has a sign in the problem that points to it. Their code is in variations.ts, and node variations.ts runs each one on the input below.
Count how many of each
Suppose you want to know how many requests got each status code:
// Counting: how many requests got each status code.
// One get and one set per item: O(n) average time, O(k) extra memory, k = distinct codes.
export function countCodes(codes: number[]): Map<number, number> {
const counts = new Map<number, number>();
for (const code of codes) counts.set(code, (counts.get(code) ?? 0) + 1);
return counts;
}
For [200, 404, 200, 500, 200, 404], it prints Map(3) { 200 => 3, 404 => 2, 500 => 1 }. ?? 0 gives the first count of a code a starting value. The keys stay numbers, because a Map keeps any value as a key.
The sign is “how many of each” or “the most common”. The memory is O(k) for k distinct keys, which can be much less than n. Exercise 1 counts order statuses this way.
Group items by a key
Now suppose you want the paths each user requested, in log order:
// Grouping: the paths each user requested, in log order.
// getOrInsertComputed returns the user's array, creating it on first use.
// O(n) average time, O(n) extra memory.
export type Request = { user: string; path: string };
export function pathsByUser(requests: Request[]): Map<string, string[]> {
const groups = new Map<string, string[]>();
for (const { user, path } of requests) groups.getOrInsertComputed(user, () => []).push(path);
return groups;
}
map.getOrInsertComputed(key, callback) returns the value stored under key. If there is none, it first stores callback(key) under it. It is new in Node.js 26. For three requests from ana, ben and ana, pathsByUser prints Map(2) { 'ana' => [ '/cart', '/pay' ], 'ben' => [ '/' ] }.
When you have the whole list and want whole items in each group, Map.groupBy(items, callback) builds the map in one call. It puts each item under the key callback(item).
The sign is “all X for each Y”. Write the loop when items arrive one at a time, or when you keep only part of each item. Exercise 2 groups orders by customer.
Look up an earlier running total
Module 2 ended with a case its window could not handle, a total of values that can be negative. Suppose you have the daily changes in a product’s stock. You want the longest run of days after which the stock is back where it started, so the changes in that run add up to 0. Some changes are negative, so Module 2’s growing window gives wrong answers.
A running total is the sum of all changes up to a point. For the changes [2, -1, 3], the running totals are 2, 1 and 4. If the running total after day j equals the running total after an earlier day i, the days in between add up to 0. So keep a Map from each running total to the first point where it appeared:
// Remembering earlier totals: the longest run of days after which the stock is back
// where it started (the changes in the run add up to 0). Changes can be negative.
// `firstAt` maps a running total to the first point where it appeared; the same total
// seen again means the days in between add up to 0. O(n) average time, O(n) memory.
export function longestNetZero(changes: number[]): { start: number; length: number } {
const firstAt = new Map<number, number>([[0, 0]]); // a total of 0 before day 0
let total = 0;
let best = { start: 0, length: 0 };
for (let day = 0; day < changes.length; day++) {
total += changes[day];
const start = firstAt.get(total);
if (start === undefined) firstAt.set(total, day + 1);
else if (day + 1 - start > best.length) best = { start, length: day + 1 - start };
}
return best;
}
Figure 5 traces longestNetZero([2, -1, 3, -2, -2, 1, 4]), for which node variations.ts prints { start: 0, length: 5 }.
changes [2] [-1] [3] [-2] [-2] [1] [4]
0 1 2 3 4 5 6
firstAt starts as { 0 -> 0 }: a total of 0 before day 0
day change total firstAt.get(total) action best
0 2 2 undefined set 2 -> 1 start 0, length 0
1 -1 1 undefined set 1 -> 2 start 0, length 0
2 3 4 undefined set 4 -> 3 start 0, length 0
3 -2 2 1 days 1..3 start 1, length 3
4 -2 0 0 days 0..4 start 0, length 5
5 1 1 2 days 2..5 start 0, length 5
6 4 5 undefined set 5 -> 7 start 0, length 5
Figure 5: a total seen before means the days since then add up to 0, and keeping only its first point gives the longest such run.
The cost is O(n) average time and O(n) memory for the Map. The sign is “a run that adds up to exactly k” when values can be negative. For a target k other than 0, look up total - k instead of total.
That last step is the general move: work out the partner you need, and look it up among what you’ve seen. Exercise 3 uses it to find two payments that add up to a total.
Underneath: how V8 stores a Map and a Set
The V8 facts in this module hold as of V8 14.6.202.34, the version in Node.js 26.13.1.
V8 keeps a Map or a Set in one block of memory with the same parts as ToyHashSet, as the V8 source file ordered-hash-table.h shows. The block holds, in order:
- three counts: entries, deleted entries and buckets
- the buckets, each the index of an entry
- the entries, in insertion order: a key and a chain index for a
Set, plus a value for aMap
Figure 6 draws a Set that holds the four IDs from Figure 1. The bucket numbers come from toyHash, because V8’s own hash values differ.
counts buckets entries (key, chain)
[4] [0] [2] [2] [3] [a7][-1] [o2][-1] [c9][0] [x1][1]
0 1 0 1 2 3
Figure 6: one block holds the counts, the buckets and the entries, so V8 iterates a Set by reading its entries in order.
A new table has room for 4 entries in 2 buckets, the same as ToyHashSet. When the table fills, V8 rehashes it, usually to double the size. A rehash copies the live entries in order, so a Map or Set always iterates in the order you added the keys.
The layout also explains the memory that Module 1 measured. A slot is room for one entry, and a word is 8 bytes in this Node.js build. Per slot, a Set stores 2 words (key and chain) and half a bucket word, because there is one bucket per 2 slots. That’s 2.5 words, or 20 bytes.
A Map adds the value, so it needs 28 bytes per slot. A Set of 1,000,000 integers has 2²⁰ = 1,048,576 slots, which gives the 20.0 MB and 28.0 MB that memory.ts printed in Module 1. So the O(n) extra memory of firstDuplicate is about 20 bytes per slot, plus the strings themselves.
Underneath: how Map and Set compare keys
A hash table needs two things from a key: a hash, and a way to tell equal keys apart. Save keys.ts:
// How Map and Set decide that two keys are equal: node keys.ts
console.log("new Set([NaN, NaN, 0, -0]).size ", new Set([NaN, NaN, 0, -0]).size);
console.log("[NaN].includes(NaN) ", [NaN].includes(NaN));
console.log("[NaN].indexOf(NaN) ", [NaN].indexOf(NaN));
console.log("Map with key 1, get('1') ", new Map([[1, "number one"]]).get("1"));
console.log("Object.keys({ 1: 'one' }) ", Object.keys({ 1: "one" }));
const a = { id: 1 };
console.log("Set of a, has(a), has({ id: 1 })", new Set([a]).has(a), new Set([a]).has({ id: 1 }));
Pause and predict. NaN === NaN is false in JavaScript. What size do you expect for new Set([NaN, NaN, 0, -0])?
Run node keys.ts:
new Set([NaN, NaN, 0, -0]).size 2
[NaN].includes(NaN) true
[NaN].indexOf(NaN) -1
Map with key 1, get('1') undefined
Object.keys({ 1: 'one' }) [ '1' ]
Set of a, has(a), has({ id: 1 }) true false
Map and Set compare keys with SameValueZero, which is === except that NaN equals NaN, as the ECMAScript specification defines it. So the set keeps one NaN, and 0 and -0 are one key. includes uses the same comparison, but indexOf uses ===, which is why it can’t find NaN.
The number 1 and the string "1" are different keys in a Map. An object turns every key into a string, so Object.keys gives back '1'.
An object used as a key is equal only to itself. V8 gives each object a random hash the first time it needs one. It stores the hash with the object, as the V8 blog post Optimizing hash tables: hiding the hash code (2018) explains. The object’s contents play no part, so { id: 1 } and another { id: 1 } are two keys.
Underneath: objects versus Map as dictionaries
A dictionary is a structure that maps keys to values. A plain object is the other common dictionary in JavaScript, and you’ll meet code that counts with one. map-vs-object.ts counts orders per customer both ways. Here is an excerpt with the two counting benchmarks; the full file also times adding keys and then deleting them all:
// Counting orders per customer: a Map against a plain object used as a dictionary.
import { bench } from "./bench.ts";
// n customer names drawn from n / 10 distinct customers.
const names = (n: number): string[] =>
Array.from({ length: n }, () => `cust-${Math.floor(Math.random() * (n / 10))}`);
const sizes = [100_000, 1_000_000, 4_000_000];
bench("count with a Map", sizes, names, (list) => {
const counts = new Map<string, number>();
for (const name of list) counts.set(name, (counts.get(name) ?? 0) + 1);
return counts;
});
bench("count with an object", sizes, names, (list) => {
const counts: Record<string, number> = {};
for (const name of list) counts[name] = (counts[name] ?? 0) + 1;
return counts;
});
Pause and predict. Will the object be several times faster than the Map, about the same, or slower?
Here are the two counting tables from node map-vs-object.ts:
count with a Map
n median ms x prev
100,000 19.91
1,000,000 199.21 10.0
4,000,000 1785.84 9.0
count with an object
n median ms x prev
100,000 12.48
1,000,000 267.50 21.4
4,000,000 1596.91 6.0
Neither wins everywhere. The object counted faster at 100,000 and 4,000,000 names, and the Map at 1,000,000. Every row stays within about 1.6 times of its partner. The growth columns jump between 6.0 and 21.4, so read these numbers as “about the same”, not as a ranking.
Why isn’t the object faster, when V8 is known for fast property reads?
V8 reads a property fast when an object has a few fixed keys, as the V8 blog post Fast properties in V8 (2017) explains. An object with many computed keys doesn’t fit that case. So V8 moves its properties into a hash table of its own, which is called dictionary mode. In other words, an object used as a dictionary becomes a hash table too, which is why the times match.
Speed doesn’t decide, so the behavior does. A Map differs from an object in five ways that matter for a dictionary of data:
- Keys: a
Mapkeeps any value as a key, and an object turns keys into strings. - Inherited names: a
{}already answers toconstructor,toStringand__proto__, fromObject.prototype. AMapstarts empty. - Size: a
Maphassize. For an object,Object.keys(o).lengthbuilds an array of every key, O(n). - Order: a
Mapiterates in insertion order. An object lists integer-like keys first, in ascending order, then the other strings in insertion order, as the ECMAScript specification defines. - Delete: a
Mapmarks an entry as deleted. On an object,deleteswitches it to dictionary mode.
Use a Map for a dictionary whose keys come from data. Use an object for a record with a fixed set of names that you know when you write the code, like an Order. V8 keeps those fast, and they turn into JSON directly. Object.create(null) gives an object with no inherited names, but the other four differences stay.
Underneath: when sorting beats hashing
Sorting answers some of the same questions. After a sort, equal IDs sit next to each other, so one pass over neighbors finds a repeat. Add hasDuplicateBySorting to duplicates.ts:
// Sort a copy of the IDs, then equal IDs sit next to each other.
// O(n log n) time, O(n) extra memory for the copy. Answers "is there a duplicate?",
// but not "which order came first", because sorting loses the original order.
export function hasDuplicateBySorting(orders: Order[]): boolean {
const ids = orders.map((o) => o.id).sort();
for (let i = 1; i < ids.length; i++) {
if (ids[i] === ids[i - 1]) return true;
}
return false;
}
sort() with no compare function sorts values as strings, which is right here because the IDs are strings. The cost is O(n log n) comparisons, and each comparison of two strings reads characters until they differ. It answers a weaker question than firstDuplicate: whether some ID repeats, not which order repeated first.
Here are the last two tables of node measure-duplicates.ts, which you can now run yourself:
hasDuplicateBySorting
n median ms x prev
5,000 1.48
10,000 2.70 1.8
20,000 6.54 2.4
hasDuplicateBySorting, larger
n median ms x prev
100,000 33.42
1,000,000 559.18 16.7
The sort kept up with the Set at every size. At 20,000 orders it took 6.54 ms against 6.47 ms, and at 1,000,000 it took 559.18 ms against 656.15 ms. O(n log n) against O(n) predicts the opposite. But log n grows slowly, and the Set pays extra the first time it sees each fresh string, as “Going deeper” measures.
The choice flips with what the problem needs:
- Sort when the output must be sorted anyway, or when you need neighbors or ranges (“the closest two”, “how many between a and b”). Also when the data is already sorted.
- Hash when you need the first occurrence or the original order, or when items arrive one at a time. Also for counts and groups, and for keys that don’t compare cheaply.
What changed in Map and Set since 2024
Map.groupBy(ES2024) builds aMapof groups in one call. It runs on Node.js 22 and later, as the TC39 list of finished proposals shows.- Set methods (ES2025):
union,intersection,difference,symmetricDifference,isSubsetOf,isSupersetOfandisDisjointFrom. V8 12.4 ships them, so Node.js 22.0 and later have them.new Set(a).difference(new Set(b))is a newSetof the items ofathat are not inb. getOrInsertandgetOrInsertComputed(ES2026) onMapreached stage 4, the last step before the standard, in January 2026. V8 ships them from version 14.5, behind thejs_upsertflag inflag-definitions.h. So Node.js 26.0.0 (2026-05-05) is the first Node.js release that has them without a flag.
“Going deeper” covers two changes to string keys inside V8, from 2025.
Common mistakes
Counting with a plain object. A key that is also a name on Object.prototype starts with an inherited value. mistakes.ts counts the statuses ["paid", "constructor", "paid", "toString"] with counts[s] = (counts[s] ?? 0) + 1 and prints:
1. {
paid: 2,
constructor: 'function Object() { [native code] }1',
toString: 'function toString() { [native code] }1'
}
Map: Map(3) { 'paid' => 2, 'constructor' => 1, 'toString' => 1 }
counts["constructor"] was the Object function, not undefined, so ?? 0 never applied and + 1 joined it to a string. Count with a Map, as the second line does.
Expecting insertion order from an object. Keys added in the order "30", "b", "10", "a", "2" come back from Object.keys as [ '2', '10', '30', 'b', 'a' ]. A Map returns [ '30', 'b', '10', 'a', '2' ]. If order matters and keys can look like numbers, use a Map.
Objects and arrays as keys. seen.set({ id: 1 }, 1) followed by seen.get({ id: 1 }) gives undefined, because the second { id: 1 } is another object. new Set([[1, 2], [1, 2]]).size is 2, and new Set(["1,2", "1,2"]).size is 1. Use a primitive key, such as the id.
Writing map[key] instead of map.set. wrong["paid"] = 1 on a Map leaves wrong.size at 0 and wrong.get("paid") at undefined. The value went onto the Map object as an ordinary property, and the table never saw it. Use set and get.
A composite key with a separator that can appear in its parts. `${x}-${y}` gives the same key for ("a-b", "c") and ("a", "b-c"). So mistakes.ts prints true for that comparison. JSON.stringify([x, y]) keeps them apart and prints false. Use a separator that can’t occur in the parts, or JSON.stringify of an array.
indexOf to look for NaN. [NaN].indexOf(NaN) is -1, as keys.ts printed, because indexOf uses ===. Use includes, or a Set, which use SameValueZero.
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 17 tests fail until you write the five functions. The tests for Exercises 3, 4 and 5 also time the function on a large input, so a correct answer that scans fails. A version of Exercise 4 that calls received.includes for every expected ID passed the first two tests and failed the third with took 21061 ms.
Exercise 1: orders per status (easy)
Write countByStatus(orders): a Map from each status to the number of orders in it, in the order each status first appears. Start from exercises/count-by-status.ts:
// How many orders are in each status? Return a Map from status to count.
// Target: O(n) time.
export type Order = { id: string; status: string };
export function countByStatus(orders: Order[]): Map<string, number> {
throw new Error("not implemented");
}
The tests check the order of the statuses, a status named constructor, and an empty list.
Hint
Use the counting shape from countCodes. What does counts.get(status) return the first time you see a status?
Solution
// How many orders are in each status? Return a Map from status to count.
// One pass, one Map lookup and one update per order: O(n) average time,
// O(k) extra memory, k = number of distinct statuses.
export type Order = { id: string; status: string };
export function countByStatus(orders: Order[]): Map<string, number> {
const counts = new Map<string, number>();
for (const { status } of orders) counts.set(status, (counts.get(status) ?? 0) + 1);
return counts;
}
Cost: O(n) average time, one lookup and one update per order. O(k) extra memory for k distinct statuses. A Map keeps the statuses in the order they first appear, and a status named constructor is an ordinary key.
Exercise 2: orders per customer (easy)
Write groupByCustomer(orders): a Map from each customer to that customer’s orders, in list order. Start from exercises/group-by-customer.ts:
// Group orders by customer: a Map from customer to that customer's orders, in list order.
// Target: O(n) time.
export type Order = { id: string; customer: string };
export function groupByCustomer(orders: Order[]): Map<string, Order[]> {
throw new Error("not implemented");
}
The tests check the order of customers and of their orders, compare your answer with Map.groupBy on 1,000 orders, and check an empty list. Write the loop yourself, not Map.groupBy.
Hint
For each order, get the customer’s array from the Map, creating it if this is the customer’s first order, then push the order.
Solution
// Group orders by customer: a Map from customer to that customer's orders, in list order.
// One Map lookup and one push per order: O(n) average time, O(n) extra memory.
// Map.groupBy(orders, (o) => o.customer) does the same (ES2024; runs on Node.js 22 and later).
export type Order = { id: string; customer: string };
export function groupByCustomer(orders: Order[]): Map<string, Order[]> {
const groups = new Map<string, Order[]>();
for (const order of orders) {
let group = groups.get(order.customer);
if (!group) {
group = [];
groups.set(order.customer, group);
}
group.push(order);
}
return groups;
}
Cost: O(n) average time, one lookup and one push per order. O(n) extra memory, because every order goes into one array. On Node.js 26 the body of the loop can be one line, groups.getOrInsertComputed(order.customer, () => []).push(order), as in pathsByUser.
Exercise 3: two payments that match a total (medium)
Write pairWithTotal(amounts, total). amounts is not sorted. Return the indexes of two different payments that add up to total, smaller index first, or null. Module 2 solved this for a sorted list.
Start from exercises/pair-with-total.ts:
// Two payments in an unsorted list that add up to `total`: return their indexes, or null.
// Target: O(n) time. (Module 2 solved this for a sorted list with two pointers.)
export function pairWithTotal(amounts: number[], total: number): [number, number] | null {
throw new Error("not implemented");
}
The tests check that one payment is never used twice, a list with no pair, an empty list, and that 200,000 amounts with no pair take under 200 ms.
Hint
For each amount, which partner would it need? Keep the amounts you’ve seen in a Map. What should the Map return, so that you can give back an index?
Solution
// Two payments in an unsorted list that add up to `total`: return their indexes, or null.
// For each amount, ask a Map whether its partner (total - amount) came earlier.
// O(n) average time, O(n) extra memory. Sorting plus two pointers would be
// O(n log n) time and would need the original indexes carried along.
export function pairWithTotal(amounts: number[], total: number): [number, number] | null {
const indexOf = new Map<number, number>();
for (let i = 0; i < amounts.length; i++) {
const partner = indexOf.get(total - amounts[i]);
if (partner !== undefined) return [partner, i];
indexOf.set(amounts[i], i);
}
return null;
}
Cost: O(n) average time, one lookup and one insert per amount. O(n) extra memory for the Map. Looking up the partner before adding the current amount is what stops [5, 9] with a total of 10 from using the 5 twice.
Exercise 4: IDs that never arrived (medium)
Write missingIds(expected, received): the expected order IDs that are not among the received ones, in the order of expected. Start from exercises/missing-ids.ts:
// Which expected order IDs never arrived? Return them in the order of `expected`.
// Target: O(e + r) time, e = expected.length, r = received.length.
export function missingIds(expected: string[], received: string[]): string[] {
throw new Error("not implemented");
}
The tests check the order of the result, the cases with nothing missing and nothing received, and that 100,000 expected and 90,000 received IDs take under 200 ms.
Hint
received.includes(id) inside a loop over expected is O(e · r). Which structure answers “is this ID among the received ones?” in O(1)?
Solution
// Which expected order IDs never arrived? Return them in the order of `expected`.
// Put the received IDs in a Set, then keep each expected ID the Set lacks.
// O(e + r) average time, O(r) extra memory.
// With ES2025 Set methods: [...new Set(expected).difference(new Set(received))]
// (runs on Node.js 22 and later), which also drops repeated expected IDs.
export function missingIds(expected: string[], received: string[]): string[] {
const got = new Set(received);
return expected.filter((id) => !got.has(id));
}
Cost: O(r) to build the Set and O(e) for the filter, so O(e + r) average time. O(r) extra memory. The difference version in the comment builds a second Set of the expected IDs, so it also drops an ID that is expected twice.
Exercise 5: the longest streak of active days (harder)
A user’s active days are day numbers, in any order and maybe repeated. Write longestStreak(days): the length of the longest run of consecutive days, such as 5, 6, 7 for a run of 3. Don’t sort. Start from exercises/longest-streak.ts:
// A user's active days, as day numbers in any order, maybe repeated.
// Return the length of the longest run of consecutive days (5, 6, 7 is a run of 3).
// Target: O(n) average time, without sorting.
export function longestStreak(days: number[]): number {
throw new Error("not implemented");
}
For [10, 4, 12, 11, 5, 1, 13] the answer is 4 (10, 11, 12, 13). The tests also check repeated days, an empty list, one day, and that one run of 300,000 shuffled days takes under 300 ms.
Hint
Put the days in a Set, then count upward with has(day + 1). If you count from every day, a run of length n costs O(n²). From which days is it enough to start counting?
Solution
// A user's active days, as day numbers in any order, maybe repeated.
// Return the length of the longest run of consecutive days (5, 6, 7 is a run of 3).
// Put the days in a Set. Only start counting at a day whose previous day is absent,
// so every day is visited by at most one count: O(n) average time, O(n) extra memory.
// Sorting first and scanning neighbours also works, in O(n log n) time.
export function longestStreak(days: number[]): number {
const active = new Set(days);
let best = 0;
for (const day of active) {
if (active.has(day - 1)) continue; // not the first day of its run
let length = 1;
while (active.has(day + length)) length++;
best = Math.max(best, length);
}
return best;
}
Cost: O(n) average time. The while loop runs only from the first day of each run, so over the whole function it visits each day once, and each other day costs one has. O(n) extra memory for the Set, which also removes repeated days.
Going deeper
You can skip this section. It covers V8 details that the main path left out.
How a V8 table grows and shrinks
The rules in V8 14.6, from ordered-hash-table.cc:
- Grow: when the entries, deleted ones included, fill the table, V8 rehashes. If at least half of them are deleted, it rehashes at the same size, which drops them. Otherwise it doubles the capacity.
- Shrink: when live entries fall below a quarter of the capacity, it rehashes to half the size.
- Order: an iterator that is running during a rehash moves over to the new table.
The header of ordered-hash-table.h says the design is the “deterministic hash table” that Jason Orendorff described for Mozilla, first attributed to Tyler Close. Many other hash tables use open addressing instead, where entries live in the bucket array itself and a key that collides takes the next free slot. Orendorff estimates that the Close design uses about 20% more memory than the leanest open-addressing table. He also reports that it measured faster, especially for inserts, on his 2012 page Deterministic hash tables.
How V8 hashes numbers and strings
V8 computes the hash from the kind of key, in Object::GetSimpleHash in objects-inl.h:
- Small integers hash from their value.
- Other numbers:
NaNhas one fixed hash, and a number with an integer value hashes like that integer, so-0lands with0. Other numbers hash their 64 bits. - Strings hash from their characters. V8 computes the hash once and stores it in the string, so a second lookup with the same string doesn’t read the characters again.
V8 13.4 switched string hashing to rapidhash, the hash function Chromium uses, in V8 commit d329f49 (2025-01-24). Node.js 24 is the first release line with it.
The first use of a string key costs the most
first-use.ts builds a Set from fresh string IDs, and from IDs that were already used once as Set keys while the input was built:
// The first time a string is used as a Map or Set key costs more than later uses.
import { bench } from "./bench.ts";
const sizes = [100_000, 1_000_000];
// Fresh 10-character IDs, never used as keys before: the case in firstDuplicate.
const freshIds = (n: number): string[] => Array.from({ length: n }, () => Math.random().toString(36).slice(2, 12));
// The same kind of IDs, already used once as Set keys while building the input.
const usedIds = (n: number): string[] => {
const ids = freshIds(n);
new Set(ids);
return ids;
};
const numbers = (n: number): number[] => Array.from({ length: n }, (_, i) => i * 7);
bench("new Set of fresh string IDs", sizes, freshIds, (ids) => new Set(ids).size);
bench("new Set of string IDs used as keys before", sizes, usedIds, (ids) => new Set(ids).size);
bench("new Set of small integers", sizes, numbers, (ns) => new Set(ns).size);
Run node first-use.ts:
new Set of fresh string IDs
n median ms x prev
100,000 37.27
1,000,000 545.16 14.6
new Set of string IDs used as keys before
n median ms x prev
100,000 6.53
1,000,000 121.30 18.6
new Set of small integers
n median ms x prev
100,000 7.43
1,000,000 113.57 15.3
IDs used before were 4.5 times faster at 1,000,000 (121.30 ms against 545.16 ms), about as fast as integers. The difference is the first use. Since V8 14.2, a Map or Set internalizes every string key before it looks it up. To internalize a string is to find or add its one shared copy in V8’s table of unique strings.
For a fresh string, that means a call from the Set code into V8’s C++ runtime, which also computes the hash. The call is Runtime::kInternalizeString, in builtins-collections-gen.cc. A string that was used as a key before is already internalized, or points to its shared copy, and its hash is stored. So later lookups skip that work.
In firstDuplicate every ID is fresh, so the first-use cost is in every row of its table. It is still O(1) per key on average, so it doesn’t change the Big O. The change came in V8 commit 2312ab9 (2025-09-19), which says it “reduces lookup cost”. Node.js 26 is the first release line with it.
When V8 switches an object to dictionary mode
dictionary-mode.js shows when V8 moves an object’s properties into a hash table:
// When V8 switches an object's properties to a hash table (dictionary mode).
// Plain JavaScript, because %HasFastProperties is a V8 debugging helper:
// node --allow-natives-syntax dictionary-mode.js
const o = {};
let i = 0;
while (%HasFastProperties(o)) {
o["k" + i] = i; // a computed key, as in a dictionary
i++;
}
console.log(`{} with computed keys: dictionary mode after key number ${i}`);
const literal = { a: 1, b: 2, c: 3 };
console.log("{ a, b, c } fast:", %HasFastProperties(literal));
delete literal.a;
console.log("after delete .a fast:", %HasFastProperties(literal));
{} with computed keys: dictionary mode after key number 20
{ a, b, c } fast: true
after delete .a fast: false
A store with a computed key switches the object when its properties outside the object itself pass a limit. The flag behind that limit is fast_properties_soft_limit, 12 by default, read by Map::TooManyFastProperties in map-inl.h. In this run it happened at the 20th key.
A delete switched the small object at once. So every counting object in map-vs-object.ts was in dictionary mode after about 20 customers. The two delete benchmarks in that file show the same “about the same speed” result as the counting ones.
Sorting numbers in a typed array
A typed array, such as Float64Array, keeps its numbers in one block of 8-byte values. sort-vs-set.ts asks “is there a duplicate?” of distinct random numbers in three ways:
// "Is there a duplicate?" on numbers: a Set against sorting a typed array.
import { bench } from "./bench.ts";
const sizes = [100_000, 1_000_000, 10_000_000];
// Distinct random doubles: no duplicate, the worst case for both.
const values = (n: number): number[] => Array.from({ length: n }, () => Math.random());
bench("Set", sizes, values, (list) => new Set(list).size !== list.length);
bench("Float64Array.from(list).sort(), then compare neighbours", sizes, values, (list) => {
const sorted = Float64Array.from(list).sort(); // typed arrays sort numerically by default
for (let i = 1; i < sorted.length; i++) if (sorted[i] === sorted[i - 1]) return true;
return false;
});
bench("list.sort((a, b) => a - b), then compare neighbours", sizes, values, (list) => {
list.sort((a, b) => a - b);
for (let i = 1; i < list.length; i++) if (list[i] === list[i - 1]) return true;
return false;
});
Run node sort-vs-set.ts:
Set
n median ms x prev
100,000 8.59
1,000,000 222.26 25.9
10,000,000 5193.34 23.4
Float64Array.from(list).sort(), then compare neighbours
n median ms x prev
100,000 9.42
1,000,000 91.03 9.7
10,000,000 1076.81 11.8
list.sort((a, b) => a - b), then compare neighbours
n median ms x prev
100,000 38.77
1,000,000 509.33 13.1
10,000,000 7994.38 15.7
At 10,000,000 numbers, sorting a Float64Array took 1,076.81 ms, and the Set took 5,193.34 ms, almost 5 times longer. With no compare function, a typed array’s sort calls no JavaScript function for each comparison. A plain array sorted with a compare function was the slowest of the three.
The Set grew more than 20 times per 10 times more numbers. Its table of 10,000,000 entries has 16,777,216 slots of 20 bytes, about 335 MB, so most lookups go far outside the CPU cache. So for numbers, and when memory is tight, a sorted typed array is worth trying.
A sort in place also changes the caller’s array. list.sort in the third benchmark does that, which is fine there only because bench.ts gives every run a fresh input.
Cheat sheet
Figure 7 is the summary of the module: which shape fits which sign in a problem.
sign in the problem shape cost
"seen before?", "is X in Y?" inside a loop Set of seen items O(n)
"how many of each", "most common" Map key -> count O(n)
"all X for each Y" Map key -> array O(n)
two items that combine to a target Map value -> index O(n)
a run that adds up to exactly k, negatives Map total -> index O(n)
sorted output, neighbours or ranges needed sort, then scan O(n log n)
Figure 7: if the slow version scans earlier items to answer a lookup, a Set or a Map built as you go removes the scan.
- Hash table: hash the key, read one bucket, compare the few keys in it. O(1) on average, O(n) when keys share a bucket.
- Growth: at 2 entries per bucket the table doubles its buckets, so an add is amortized O(1).
- Seen before: a
Setof seen IDs took 20,000 orders from 1,449.19 ms to 6.47 ms, for O(n) extra memory. - Counting and grouping:
counts.set(k, (counts.get(k) ?? 0) + 1);getOrInsertComputed(k, () => [])orMap.groupBy. - Partners and totals: a
Mapfrom a value or a running total to its first index; look uptotal - k. - Keys: SameValueZero, so
NaNfindsNaN; objects compare by identity, so key by a primitive such as theid. Mapor object: about the same speed; aMapfor keys that come from data, an object for records with fixed names.- Sort or hash: sort for sorted output, neighbors and ranges; hash for first occurrence, items that arrive one at a time, counts and groups.
- Next: Module 4 builds linked lists, and joins a list with a
Mapto make a cache that evicts its least recently used entry.
Sources
- V8 source at 14.6.202.34, the version in Node.js 26.13.1:
ordered-hash-table.handordered-hash-table.cc(layout, growth),objects-inl.h(GetSimpleHash),builtins-collections-gen.cc(internalizing string keys),map-inl.h(TooManyFastProperties),flag-definitions.h. - V8 commits: rapidhash for strings (2025), internalize string keys (2025).
- V8 blog: Optimizing hash tables: hiding the hash code (2018), Fast properties in V8 (2017).
- Jason Orendorff, Deterministic hash tables (2012).
- ECMAScript specification: Map objects, Set objects, SameValueZero, OrdinaryOwnPropertyKeys; TC39 finished proposals (
Map.groupBy, Set methods, upsert).