Data Structures and Algorithms, Pattern by Pattern / Module 02

Module 2: Arrays and Strings: Two Pointers, Sliding Windows, Prefix Sums

Find the busiest minute in a request log in one pass with two pointers, sliding windows and prefix sums, and see how V8 stores arrays and strings.

Suppose you have one day of request times from a server log, in seconds since midnight and sorted, and you want the busiest minute. Here is a correct function that finds it. Save it as busiest.ts:

// The busiest minute in a request log.
// `times` holds request times in seconds since midnight, sorted ascending.
// A minute is any 60-second window [start, start + 60). The busiest one can always
// start at a request time, so we only try those starts. Ties go to the earliest start.

export type Busiest = { start: number; count: number };

// For every request, re-scan the whole log: O(n^2) time, O(1) extra memory.
export function busiestSlow(times: number[]): Busiest {
  let best: Busiest = { start: 0, count: 0 };
  for (const start of times) {
    let count = 0;
    for (const t of times) {
      if (t >= start && t < start + 60) count++;
    }
    if (count > best.count) best = { start, count };
  }
  return best;
}

In one run on a log of 500,000 requests, busiestSlow took 248 seconds. The version you’ll write in this module took 0.004 seconds on the same log. This module removes the re-scan, then shows how V8 stores the arrays and strings these patterns walk over.

After this module, you can:

  • replace a re-scan inside a loop with a sliding window whose two pointers only move forward, and explain why that is O(n)
  • answer many “how many between a and b” questions in O(1) each with prefix sums, and say when building them is not worth it
  • pick the shape a problem needs: two pointers from both ends, a read and a write pointer, a fixed window, or a window that grows and shrinks
  • say how V8 stores an array’s elements and a string’s characters, and predict when += in a loop stays O(n) and when it becomes O(n²)

Measure the re-scan at three sizes

Make a folder for the module, as in Module 1, and copy bench.ts into it unchanged:

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

Then save measure-busiest.ts. It builds a log of n random request times in one day, sorted, and times all three versions of the function. Two of them don’t exist yet, so read the first table now. Run the script yourself after the section on prefix sums.

import { bench } from "./bench.ts";
import { busiestSlow, busiestWindow, busiestByPrefix, SECONDS } from "./busiest.ts";

// n requests at random whole seconds of one day, sorted.
const log = (n: number): number[] =>
  Array.from({ length: n }, () => Math.floor(Math.random() * SECONDS)).sort((a, b) => a - b);

bench("busiestSlow", [10_000, 20_000, 40_000], log, busiestSlow);
bench("busiestWindow", [10_000, 20_000, 40_000], log, busiestWindow);
bench("busiestByPrefix", [10_000, 20_000, 40_000], log, busiestByPrefix);
bench("busiestWindow, larger", [100_000, 1_000_000, 10_000_000], log, busiestWindow);
bench("busiestByPrefix, larger", [100_000, 1_000_000, 10_000_000], log, busiestByPrefix);

Pause and predict. busiestSlow runs its inner loop over all n times, once for each of the n times. When the log doubles, how many times longer does it take?

Here is the first table that node measure-busiest.ts printed:

busiestSlow
             n   median ms   x prev
        10,000       96.45
        20,000      382.89      4.0
        40,000     1540.91      4.0

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 4.0 times slower, so busiestSlow is O(n²), as its two nested loops over times say. At 500,000 requests, that is 2.5 × 10¹¹ comparisons. Module 1 set a budget of about 10⁸ simple steps per second, so this is far over it.

Slide a window instead of re-scanning

The code writes a minute as [start, start + 60). The square bracket means second start is inside the minute, and the round bracket means second start + 60 is not. So [10, 70) holds seconds 10 through 69, and a request at second 70 is not in it.

Now look at what the inner loop repeats. For the minute starting at 70, it counts every request in [70, 130). For the next start, 100, it counts [100, 160) from scratch, although most of those requests were in the last count.

Because times is sorted, the requests in a minute sit next to each other in the array. So two indexes can describe the minute. left is the first request in the minute, right is the first request after it, and the count is right - left.

A sliding window is a run of consecutive items, marked by two indexes, that moves forward through an array. When left moves to the next start, the end of the minute moves forward too, so right never has to move back. Two pointers means two indexes into the same array that each move in only one direction. Together they make at most about 2n moves.

Figure 1 traces the example log from the tests, [5, 30, 64, 70, 100, 125, 128, 129].

times  [5] [30] [64] [70] [100] [125] [128] [129]
        0    1    2    3    4     5     6     7

left  times[left]  minute       right after the step  count  best
  0        5       [5, 65)               3              3     5: 3
  1       30       [30, 90)              4              3     5: 3
  2       64       [64, 124)             5              3     5: 3
  3       70       [70, 130)             8              5    70: 5
  4      100       [100, 160)            8              4    70: 5
  5      125       [125, 185)            8              3    70: 5
  6      128       [128, 188)            8              2    70: 5
  7      129       [129, 189)            8              1    70: 5

at left = 3, the window holds 70, 100, 125, 128, 129:
       [5] [30] [64] [70] [100] [125] [128] [129]
                      ^left                          ^right (8, past the end)

Figure 1: right only moves forward, so over the whole run it moves 8 times, once per request.

Add busiestWindow to busiest.ts:

// Sliding window with two pointers: `right` only moves forward, so the inner loop
// runs at most n times in total. O(n) time, O(1) extra memory.
export function busiestWindow(times: number[]): Busiest {
  let best: Busiest = { start: 0, count: 0 };
  let right = 0;
  for (let left = 0; left < times.length; left++) {
    while (right < times.length && times[right] < times[left] + 60) right++;
    if (right - left > best.count) best = { start: times[left], count: right - left };
  }
  return best;
}

It still has a loop inside a loop, so why isn’t it O(n²)?

The inner while does not start over. right keeps its value from the last pass, so the while runs at most n times in total, over the whole function. The outer loop runs n times too. So busiestWindow is O(n) time and O(1) extra memory.

Rule: Count the moves of each pointer over the whole run, not per pass of the outer loop. If no pointer moves back, the total is O(n).

Here are the next tables from the same run:

busiestWindow
             n   median ms   x prev
        10,000        0.11
        20,000        0.21      2.0
        40,000        0.44      2.1

busiestWindow, larger
             n   median ms   x prev
       100,000        0.82
     1,000,000        3.37      4.1
    10,000,000       23.64      7.0

Doubling the log doubles the time, as O(n) predicts. At 40,000 requests, busiestWindow takes 0.44 ms against 1,540.91 ms for busiestSlow, about 3,500 times less. Figure 2 draws both at the same three sizes.

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

n = 10,000   slow ###                                                  96.45
             fast |                                                     0.11
n = 20,000   slow ############                                        382.89
             fast |                                                     0.21
n = 40,000   slow ##################################################  1540.91
             fast |                                                     0.44

Figure 2: the re-scan grows 4 times per doubling and the window 2 times, so the gap doubles with every doubling.

At the larger sizes, the window grew less than 10 times for each 10 times more requests, and bench.ts can’t tell you why. But it never grows faster than the input, which is all that O(n) promises.

Count once, then answer any range with prefix sums

The window answers one question in one pass. Now suppose a dashboard asks many questions about the same log: how many requests between 9:00 and 9:15, between 12:00 and 12:01, and so on. Each window pass costs O(n), so q questions cost O(n · q).

The fix is to do the counting once. Make an array before, where before[s] is the number of requests before second s. Then the number of requests in [from, to) is before[to] - before[from], one subtraction. Prefix sums are running totals like these, in which entry i holds the total of the first i items.

Figure 3 builds before for a tiny log that only covers the first 8 seconds of a day, [0, 1, 1, 3, 4, 4, 4, 6].

second         0   1   2   3   4   5   6   7
count         [1] [2] [0] [1] [3] [0] [1] [0]

s              0   1   2   3   4   5   6   7   8
before[s]     [0] [1] [3] [3] [4] [7] [7] [8] [8]

requests in [1, 5) = before[5] - before[1] = 7 - 1 = 6
check:               2 + 0 + 1 + 3          = 6

Figure 3: before has one more entry than there are seconds, and before[0] = 0, so every range is one subtraction.

before[0] is 0, because no request comes before second 0. That extra leading entry is what makes [0, to) work without a special case.

Add the prefix-sum version to busiest.ts:

// Prefix sums over the seconds of the day: before[s] = requests before second s.
// Building costs O(n + S) time and O(S) memory, S = 86,400 seconds; then any range
// [from, to) costs O(1): before[to] - before[from].
export const SECONDS = 86_400;

export function prefixCounts(times: number[]): Int32Array {
  const before = new Int32Array(SECONDS + 1);
  for (const t of times) before[t + 1]++;
  for (let s = 1; s <= SECONDS; s++) before[s] += before[s - 1];
  return before;
}

export function busiestByPrefix(times: number[]): Busiest {
  const before = prefixCounts(times);
  let best: Busiest = { start: 0, count: 0 };
  for (const start of times) {
    const count = before[Math.min(start + 60, SECONDS)] - before[start];
    if (count > best.count) best = { start, count };
  }
  return best;
}

prefixCounts first adds each request to the entry after its second. Then it turns those counts into running totals. Math.min keeps a minute that starts in the last 59 seconds of the day inside the array.

before is an Int32Array. A typed array is a fixed-length array that holds only one kind of number. An Int32Array holds whole numbers of 4 bytes each, all starting at 0, so it suits a table of counts whose size you know up front.

Building before costs O(n + S) time and O(S) memory, where S is the 86,400 seconds of a day. Then each of the n questions costs O(1). Here are the last two tables from the run:

busiestByPrefix
             n   median ms   x prev
        10,000        0.53
        20,000        0.59      1.1
        40,000        1.55      2.6

busiestByPrefix, larger
             n   median ms   x prev
       100,000        1.88
     1,000,000        5.65      3.0
    10,000,000       56.78     10.0

At small sizes the time hardly moves, because the loop over 86,400 seconds costs more than the requests do. Once n is much larger than S, it grows 10.0 times for 10 times more requests, as O(n) predicts. For this one question it is slower than the window at every size: 1.55 ms against 0.44 ms at 40,000, and 56.78 ms against 23.64 ms at 10,000,000.

So prefix sums cost memory and a fixed setup, and they pay off only when you ask many range questions of data that does not change. If the log gets a new request, every entry after it is wrong until you rebuild. Exercise 4 asks many questions of one list of daily sales.

Rule: One range question: a window or a plain loop. Many range questions on the same data: prefix sums, built once.

You can now run node measure-busiest.ts yourself. The tests in busiest.test.ts check all three versions against each other on random logs. Run them with node --test busiest.test.ts.

Four more shapes of two pointers and windows

The busiest minute uses one shape. Problems that need this pattern come in a few more, and each has a sign that points to it. The three that need code are in variations.ts, and node variations.ts runs each one on the input of its figure.

Two pointers from both ends

Suppose a sorted list of numbers, [2, 4, 7, 11, 15], and you want two of them that add up to 18. Checking every pair is O(n²). Instead, put left on the smallest number and right on the largest, and look at their sum. Figure 4 traces it.

[2] [4] [7] [11] [15]      target 18
 0   1   2   3    4

step  left  right  sum            move
  1    0     4     2 + 15 = 17    too small: left++
  2    1     4     4 + 15 = 19    too large: right--
  3    1     3     4 + 11 = 15    too small: left++
  4    2     3     7 + 11 = 18    found: indexes 2 and 3

at step 4:
[2] [4] [7] [11] [15]
         ^left
             ^right

Figure 4: each step drops one number that cannot be part of the answer, so the pointers meet after at most n – 1 steps.

Each move is safe. In step 1, 2 plus the largest number is still too small, so 2 can’t pair with anything, and left drops it. In step 2, 15 plus the smallest remaining number is too large, so right drops 15. Each step removes one number, so the loop is O(n) time and O(1) extra memory.

The sign is sorted input and a question about a pair: a sum, a difference, or “closest to”. The cost is the sort. If the input isn’t sorted, sorting first costs O(n log n) and loses the original positions. A Set (Module 3) finds a pair in O(n) without sorting.

A read pointer and a write pointer

Now remove every 0 from an array in place, keeping the order of the rest. Both pointers start at the left. read visits every item, and write marks where the next kept item goes:

// Read and write pointers: remove every 0 in place and keep the order of the rest.
// `read` visits every item; `write` marks the end of the kept part.
// O(n) time, O(1) extra memory.
export function removeZeros(values: number[]): number[] {
  let write = 0;
  for (let read = 0; read < values.length; read++) {
    if (values[read] !== 0) {
      values[write] = values[read];
      write++;
    }
  }
  values.length = write;
  return values;
}

Figure 5 traces removeZeros([4, 0, 7, 0, 0, 5]), for which node variations.ts prints [ 4, 7, 5 ].

read  value  action               values after the step   write
  0     4    copy to 0, write++   [4][0][7][0][0][5]         1
  1     0    skip                 [4][0][7][0][0][5]         1
  2     7    copy to 1, write++   [4][7][7][0][0][5]         2
  3     0    skip                 [4][7][7][0][0][5]         2
  4     0    skip                 [4][7][7][0][0][5]         2
  5     5    copy to 2, write++   [4][7][5][0][0][5]         3
               0  1  2  3  4  5
values.length = 3 drops the rest: [4][7][5]

Figure 5: write never passes read, so a copy never overwrites an item that read has not visited yet.

The pointers move in the same direction at two speeds. read moves every step, and write moves only when an item is kept. The sign is “rewrite this array in place” or “no extra array”.

The cost is that the caller’s array changes. values.filter((v) => v !== 0) is also O(n), easier to read, and leaves the input alone, but it makes a new array. Use the in-place version only when that memory matters. Exercise 2 uses this shape on a sorted list.

A window of fixed size

Suppose you want the average of every 3 consecutive response times. Summing each window from scratch costs O(k) per window, O(n · k) in total. Instead, keep a running total. Each step, one item enters on the right and one leaves on the left.

// A window of fixed size k: the average of every k consecutive response times.
// One item enters and one leaves per step. O(n) time, O(1) extra memory besides the result.
export function movingAverages(ms: number[], k: number): number[] {
  const averages: number[] = [];
  let total = 0;
  for (let i = 0; i < ms.length; i++) {
    total += ms[i]; // the new item enters
    if (i >= k) total -= ms[i - k]; // the oldest item leaves
    if (i >= k - 1) averages.push(total / k);
  }
  return averages;
}

Figure 6 traces movingAverages([120, 80, 100, 300, 50], 3), for which node variations.ts prints [ 100, 160, 150 ].

ms  [120] [80] [100] [300] [50]      k = 3
      0     1    2     3     4

i  enters  leaves  total  average
0    120      -     120      -
1     80      -     200      -
2    100      -     300     100
3    300     120    480     160
4     50      80    450     150

Figure 6: the window always holds k items, so each step is one addition and one subtraction.

The sign is “k consecutive” or “every window of size k”. The limit is that you must be able to undo an item when it leaves. A sum or a count can subtract it. A maximum can’t, because when the largest item leaves, you don’t know the next largest.

Module 5 builds a structure for that case, and Exercise 3 uses this shape.

A window that grows and shrinks

busiestWindow had a window bounded by time. A window can also be bounded by what it holds. Suppose each request either succeeded or failed, and you want the longest run of requests with at most one failure:

// A window that grows and shrinks: the longest run of requests with at most `limit` failures.
// `right` adds a request; while there are too many failures, `left` drops one.
// O(n) time, O(1) extra memory.
export function longestWithFewFailures(failed: boolean[], limit: number): number {
  let left = 0;
  let failures = 0;
  let best = 0;
  for (let right = 0; right < failed.length; right++) {
    if (failed[right]) failures++;
    while (failures > limit) {
      if (failed[left]) failures--;
      left++;
    }
    best = Math.max(best, right - left + 1);
  }
  return best;
}

Figure 7 traces longestWithFewFailures([false, true, false, false, true, true, false], 1), for which node variations.ts prints 4. In the figure, x is a failed request and o one that succeeded.

failed  [o][x][o][o][x][x][o]      limit 1
         0  1  2  3  4  5  6

right  adds  failures  left after  window  length  best
  0     o       0          0       0..0      1      1
  1     x       1          0       0..1      2      2
  2     o       1          0       0..2      3      3
  3     o       1          0       0..3      4      4
  4     x     2, then 1    2       2..4      3      4
  5     x     2, then 1    5       5..5      1      4
  6     o       1          5       5..6      2      4

Figure 7: left jumps forward several places at once when needed, but it never moves back, so both pointers move at most n times.

This works because adding a request can only keep or raise the failure count, and dropping one can only keep or lower it. So once the window has too many failures, every longer window with the same left has too many as well. That’s why moving left is safe.

The sign is “the longest (or shortest) run such that…”. The cost is that this property must hold. With a sum of numbers that can be negative, dropping an item can raise the total, and the window gives wrong answers.

Prefix sums with a Map (Module 3) handle that case. Exercise 5 uses this shape with a budget.

Underneath: how V8 stores an array’s elements

V8 is the JavaScript engine inside Node.js. This section uses V8 14.6.202.34, the version in Node.js 26.13.1, and its facts hold as of that version.

V8 tracks what kind of values each array holds, so it can pick a faster way to read and write them. You can see this with V8’s debugging functions, whose names start with %. Node.js accepts them only with the --allow-natives-syntax flag, and they aren’t TypeScript, so this file is plain JavaScript. Save elements-kinds.js:

// Which elements kind V8 uses for an array. Plain JavaScript, because the %
// functions are V8 debugging helpers, not TypeScript: node --allow-natives-syntax elements-kinds.js
function kind(a) {
  if (%HasDictionaryElements(a)) return "DICTIONARY_ELEMENTS";
  const type = %HasSmiElements(a) ? "SMI_" : %HasDoubleElements(a) ? "DOUBLE_" : "";
  return (%HasHoleyElements(a) ? "HOLEY_" : "PACKED_") + type + "ELEMENTS";
}

const a = [1, 2, 3];
console.log("[1, 2, 3]                   ", kind(a));
a.push(4.5);
console.log("after push(4.5)             ", kind(a));
a.push("x");
console.log("after push('x')             ", kind(a));
a.pop();
a.pop();
console.log("after pop() twice           ", kind(a));

const b = new Array(3);
console.log("new Array(3)                ", kind(b));
b[0] = 1; b[1] = 2; b[2] = 3;
console.log("...then b[0..2] = 1, 2, 3   ", kind(b));
console.log("Array.from({ length: 3 }, f)", kind(Array.from({ length: 3 }, (_, i) => i)));
console.log("new Array(3).fill(0)        ", kind(new Array(3).fill(0)));

const c = [1, 2, 3];
c[5] = 6;
console.log("[1, 2, 3] then c[5] = 6     ", kind(c));
const d = [];
d[1024] = 1;
console.log("[] then d[1024] = 1         ", kind(d));

Pause and predict. After a.pop() twice, a holds [1, 2, 3] again. Does V8 go back to the kind it used for [1, 2, 3]? And is new Array(3), once you fill all three slots, the same as [1, 2, 3]?

Run node --allow-natives-syntax elements-kinds.js:

[1, 2, 3]                    PACKED_SMI_ELEMENTS
after push(4.5)              PACKED_DOUBLE_ELEMENTS
after push('x')              PACKED_ELEMENTS
after pop() twice            PACKED_ELEMENTS
new Array(3)                 HOLEY_SMI_ELEMENTS
...then b[0..2] = 1, 2, 3    HOLEY_SMI_ELEMENTS
Array.from({ length: 3 }, f) PACKED_SMI_ELEMENTS
new Array(3).fill(0)         PACKED_SMI_ELEMENTS
[1, 2, 3] then c[5] = 6      HOLEY_SMI_ELEMENTS
[] then d[1024] = 1          DICTIONARY_ELEMENTS

An elements kind is V8’s label for what an array’s elements are and how they’re stored. The middle of the name says what the values are:

  • SMI: every value is a small whole number, stored inside the array’s 8-byte slot itself.
  • DOUBLE: every value is a number, stored directly in its slot, as Module 1 measured.
  • Nothing: the slots can hold anything, so each slot points to a value stored elsewhere in memory.

Figure 8 shows the six common kinds and the directions they can move in.

PACKED_SMI_ELEMENTS  ->  PACKED_DOUBLE_ELEMENTS  ->  PACKED_ELEMENTS
        |                         |                          |
        v                         v                          v
HOLEY_SMI_ELEMENTS   ->  HOLEY_DOUBLE_ELEMENTS   ->  HOLEY_ELEMENTS

Figure 8: an array moves right or down when it gets a more general value or a hole, and not back, so popping the string did not undo PACKED_ELEMENTS.

The start of the name says whether the array may have gaps. A packed array has a value at every index. A holey array is one that has, or once had, an index with no value. new Array(3) starts with three such gaps, and filling the slots by index does not make it packed again.

What changed recently. A fill that replaces every element is the one way back to a packed kind. V8 added it in a change merged on 2025-02-28, Array.fill tries to transition to optimal elements kind. So Node.js 26 prints PACKED_SMI_ELEMENTS for new Array(3).fill(0), where Node.js 22.17 (V8 12.4) printed HOLEY_SMI_ELEMENTS. A fill of only part of the array leaves it holey.

Reads from a holey array need extra checks, according to the 2017 V8 blog post Elements kinds in V8. Do those checks slow a plain loop down? Save holey.ts:

// Summing a packed array and a holey one, each with its own copy of the loop.
import { bench } from "./bench.ts";

function sumPacked(a: number[]): number {
  let total = 0;
  for (let i = 0; i < a.length; i++) total += a[i];
  return total;
}
function sumHoley(a: number[]): number {
  let total = 0;
  for (let i = 0; i < a.length; i++) total += a[i];
  return total;
}

const packed = (n: number): number[] => {
  const a: number[] = [];
  for (let i = 0; i < n; i++) a.push(i);
  return a;
};
const holey = (n: number): number[] => {
  const a: number[] = new Array(n); // starts with n holes
  for (let i = 0; i < n; i++) a[i] = i;
  return a;
};

bench("sum a packed array", [1_000_000, 10_000_000], packed, sumPacked);
bench("sum a holey array", [1_000_000, 10_000_000], holey, sumHoley);

Run node holey.ts:

sum a packed array
             n   median ms   x prev
     1,000,000        1.49
    10,000,000       27.30     18.4

sum a holey array
             n   median ms   x prev
     1,000,000        1.67
    10,000,000       15.29      9.1

The holey array was not slower. The packed one took longer at 10,000,000 in this run and in three more, and bench.ts can’t tell you why. Read it as “no measurable cost of holes in this loop”, not as “holes are faster”. So build arrays with literals, push or Array.from when it’s easy, but don’t rewrite working code for this alone.

When the choice flips. The main alternative for numbers is a typed array, like the Int32Array in busiestByPrefix. It has no holes, and an Int32Array takes 4 bytes per value against 8 for an array slot.

But a typed array’s length is fixed and it has no push. It also changes values that don’t fit its type: new Int32Array([2147483648]) holds -2147483648. Use a typed array for a large table of numbers whose size you know, and a plain array everywhere else.

Underneath: how V8 stores strings, and when += stops being cheap

Building a long string with += in a loop is common in log and report code. A string can’t be changed once made, so you might expect each += to copy everything so far into a new string. That would make the loop O(n²). Save strings.ts:

// Building a long string: += against push() and join(), then reading one character.
import { bench } from "./bench.ts";

const sizes = [100_000, 1_000_000, 10_000_000];
const line = (i: number) => `req ${i}\n`;

bench("+= in a loop", sizes, (n) => n, (n) => {
  let s = "";
  for (let i = 0; i < n; i++) s += line(i);
  return s;
});

bench("push() then join()", sizes, (n) => n, (n) => {
  const parts: string[] = [];
  for (let i = 0; i < n; i++) parts.push(line(i));
  return parts.join("");
});

// The first index read flattens the cons-string tree into one flat string: O(length) once.
const built = (n: number) => {
  let s = "";
  for (let i = 0; i < n; i++) s += line(i);
  return s;
};
bench("first s.charCodeAt(0) after += (flattens)", sizes, built, (s) => s.charCodeAt(0));
bench("charCodeAt(0) on a flat string", sizes, (n) => {
  const s = built(n);
  s.charCodeAt(0); // flatten while building the input, outside the timing
  return s;
}, (s) => s.charCodeAt(0));

// Reading a character after every += flattens the whole string on every pass: O(n^2).
bench("+= and read the last character on every pass", [2_000, 4_000, 8_000], (n) => n, (n) => {
  let s = "";
  let sum = 0;
  for (let i = 0; i < n; i++) {
    s += line(i);
    sum += s.charCodeAt(s.length - 1);
  }
  return sum + s.length;
});

// Prepending also builds cons strings, so it is no slower than appending.
bench("prepend: s = line + s", sizes, (n) => n, (n) => {
  let s = "";
  for (let i = 0; i < n; i++) s = line(i) + s;
  return s;
});

Pause and predict. The first table appends 100,000, 1,000,000 and 10,000,000 lines. If every += copied the string, each row would take about 100 times longer than the one before. What do you expect instead, and how will push() then join() compare?

Run node strings.ts:

+= in a loop
             n   median ms   x prev
       100,000        9.04
     1,000,000      132.40     14.6
    10,000,000     1692.75     12.8

push() then join()
             n   median ms   x prev
       100,000        8.94
     1,000,000      206.42     23.1
    10,000,000     1988.85      9.6

first s.charCodeAt(0) after += (flattens)
             n   median ms   x prev
       100,000        1.56
     1,000,000       11.21      7.2
    10,000,000      118.84     10.6

charCodeAt(0) on a flat string
             n   median ms   x prev
       100,000        0.00
     1,000,000        0.00      2.9
    10,000,000        0.00      1.1

+= and read the last character on every pass
             n   median ms   x prev
         2,000        1.99
         4,000        7.03      3.5
         8,000       29.56      4.2

prepend: s = line + s
             n   median ms   x prev
       100,000        5.24
     1,000,000      120.25     22.9
    10,000,000     1575.09     13.1

The += loop grew 14.6 and 12.8 times for each 10 times more lines, not 100 times, so it is O(n). push() then join() is no faster: 1,988.85 ms against 1,692.75 ms for 10,000,000 lines, about 120 MB of text. Prepending with s = line + s is as cheap as appending.

A flat string is one block of characters in memory. A cons string is a small node that points to a left string and a right string, without copying their characters. So += is cheap, because V8 usually makes a cons node when you join two strings with +, which is O(1). Figure 9 shows the string after five appends of "req i\n".

s after five += (30 characters)

                    [cons 30]
                    /       \
             [cons 24]     "req 4\n"
             /       \
       [cons 18]    "req 3\n"
       /       \
"req 0\nreq 1\n"  "req 2\n"

the first two lines were copied into one flat string: under 13 characters

Figure 9: each += adds one node on top and copies no characters, so n appends cost O(n).

The bottom line of the figure is the one exception. When the result is shorter than 13 characters, V8 copies both sides into a new flat string instead, as NewConsString in factory-base.cc shows.

A tree of nodes is cheap to build but slow to index. So before V8 reads a character by position, it flattens the string: it copies all the leaves into one flat string, which costs O(length). Later reads are O(1), until the next += puts a new node on top.

Now read the third, fourth and fifth tables. The first charCodeAt(0) after the loop costs 118.84 ms at 10,000,000 lines, because it flattens about 120 MB. On a string that is already flat, it rounds to 0.00 ms.

The fifth table reads one character after every +=, so it flattens the whole string on every pass. That is O(n) per pass and O(n²) in total, and it grows 3.5 and 4.2 times per doubling. The fix is to read the piece you append (line(i)), not the whole string, or to collect the pieces in an array and join them once at the end.

Rule: Appending with += is O(1) per append until you read the string by position. Read it once at the end, not on every pass.

One more fact matters when two pointers walk a string. Strings are immutable, so you can’t swap two characters in place. In a module, s[0] = "J" throws TypeError: Cannot assign to read only property '0' of string 'hello'. Copy the characters into an array, move the pointers over it, and join at the end.

Common mistakes

left <= right in the search from both ends. When the pointers meet, the loop adds a number to itself:

// excerpt: wrong
while (left <= right) {

[5, 9] with target 10 returns [ 0, 0 ], the 5 used twice. Use left < right, so the two indexes are always different.

<= at the end of the minute. times[right] <= times[left] + 60 counts a request exactly 60 seconds later as part of the minute. On [0, 60] it returns { start: 0, count: 2 }, where the right answer is { start: 0, count: 1 }. Write the range as [start, start + 60) in a comment, and use < for the excluded end.

Prefix sums without the leading 0. If entry d holds the total up to and including day d, the array has n entries, not n + 1:

// excerpt: wrong
const upTo = new Array<number>(sales.length);
upTo[0] = sales[0];
for (let d = 1; d < sales.length; d++) upTo[d] = upTo[d - 1] + sales[d];
return queries.map(([from, to]) => upTo[to] - upTo[from]);

For the sales [5, 3, 8, 6, 2], the ranges [0, 5) and [1, 3) give [ NaN, 14 ], where the right answer is [ 24, 11 ]. upTo[5] is undefined, so the first answer is NaN, and every other range is shifted by one day. Keep before[0] = 0 and n + 1 entries, as in Figure 3.

Starting the best total at 0. Suppose a fixed window starts with best = { start: 0, total: 0 }. When every total is negative, it reports a total that no window has. [-5, -1, -3] with k = 1 returns { start: 0, total: 0 }, where the right answer is { start: 1, total: -1 }. Start best from the first full window.

Sorting times without a comparator. The window assumes sorted numbers, but sort() with no comparator sorts them as strings, as Module 1 showed. A shuffled copy of the example log sorts to [100, 125, 128, 129, 30, 5, 64, 70]. busiestWindow on it returns { start: 100, count: 8 } instead of { start: 70, count: 5 }. Use sort((a, b) => a - b).

Moving a pointer back. This version of the window restarts right on every pass. It is in pointer-back.ts, which times it against busiestWindow:

// excerpt from pointer-back.ts
for (let left = 0; left < times.length; left++) {
  let right = left; // the bug: right moves back to left on every pass
  while (right < times.length && times[right] < times[left] + 60) right++;

It gives the right answer, but right re-walks each window, so the cost is O(n · w), where w is the number of requests per minute. In a log spread over one day, w grows with n, so it’s O(n²). In one run at 4,000,000 requests it took 4,288.08 ms, against 10.18 ms for busiestWindow, and it grew 15.5 times when n grew 4 times. If a pointer moves back, count its moves again.

Exercises

The exercises are in the module’s exercises folder, each with a test file, and the solutions are in solutions. Run all the tests with:

node --test "exercises/*.test.ts"

All 19 tests fail until you write the five functions. The tests for Exercises 2 and 4 also time the function, so a correct but slow answer fails with a message such as took 7173 ms.

Exercise 1: two prices that match a total (easy)

Write pairWithTotal(prices, total). prices is sorted ascending. Return the indexes of two different prices that add up to total, or null. Start from exercises/pair-with-total.ts:

// Two prices in a sorted list that add up to `total`: return their indexes, or null.
// `prices` is sorted ascending. Target: O(n) time, O(1) extra memory.
export function pairWithTotal(prices: number[], total: number): [number, number] | null {
  throw new Error("not implemented");
}

The tests check that one price is never used twice. They also compare your answer with a check of every pair on 200 random lists.

Hint

Start one pointer at each end. If the sum is too small, which of the two prices can’t be in any pair that works?

Solution
// Two prices in a sorted list that add up to `total`: return their indexes, or null.
// Two pointers from both ends: each step moves one pointer inward, so at most n steps.
// O(n) time, O(1) extra memory.
export function pairWithTotal(prices: number[], total: number): [number, number] | null {
  let left = 0;
  let right = prices.length - 1;
  while (left < right) {
    const sum = prices[left] + prices[right];
    if (sum === total) return [left, right];
    if (sum < total) left++;
    else right--;
  }
  return null;
}

Cost: O(n) time, because each step moves one pointer inward and they meet after at most n – 1 steps. O(1) extra memory.

Exercise 2: compact a sorted list of IDs (easy)

Write compactSorted(ids). It removes repeated IDs from a sorted array in place and returns how many unique IDs remain. Start from exercises/compact-sorted.ts:

// Remove repeated IDs from a sorted array in place; return how many unique IDs remain.
// After the call, `ids` holds only the unique IDs, in order.
// Target: O(n) time, O(1) extra memory (no Set, no new array).
export function compactSorted(ids: number[]): number {
  throw new Error("not implemented");
}

The tests check these cases:

  • an empty list
  • a list with no repeats
  • a list of one repeated ID
  • 1,000,000 IDs in under 200 ms
Hint

In a sorted array, repeats sit next to each other. Use a read pointer and a write pointer. Which item should ids[read] be compared with, to know it is new?

Solution
// Remove repeated IDs from a sorted array in place; return how many unique IDs remain.
// `write` marks the end of the unique part; `read` runs ahead over every item.
// O(n) time, O(1) extra memory.
export function compactSorted(ids: number[]): number {
  if (ids.length === 0) return 0;
  let write = 1;
  for (let read = 1; read < ids.length; read++) {
    if (ids[read] !== ids[write - 1]) {
      ids[write] = ids[read];
      write++;
    }
  }
  ids.length = write;
  return write;
}

Cost: O(n) time, one pass of read. O(1) extra memory, because it writes into ids itself. Comparing with ids[write - 1], the last kept ID, works because the input is sorted.

Exercise 3: the best week of sales (medium)

Write bestWeek(sales, k): the k consecutive days with the highest total. Return the first day and the total, with ties going to the earliest start. Throw a RangeError if k is less than 1 or more than the number of days. Start from exercises/best-week.ts:

// The k consecutive days with the highest total sales: return the first day and the total.
// Ties go to the earliest start. Throw a RangeError if k < 1 or k > sales.length.
// Target: O(n) time, O(1) extra memory.
export function bestWeek(sales: number[], k: number): { start: number; total: number } {
  throw new Error("not implemented");
}

The tests include days with negative sales (refunds). They also compare your answer with a sum of every window on 100 random lists.

Hint

Sum the first k days and make that the best so far. Then, for each later day, add the day that enters and subtract the day that leaves.

Solution
// The k consecutive days with the highest total sales: return the first day and the total.
// Fixed window: add the day that enters, subtract the day that leaves.
// O(n) time, O(1) extra memory.
export function bestWeek(sales: number[], k: number): { start: number; total: number } {
  if (k <= 0 || k > sales.length) throw new RangeError("k must be between 1 and sales.length");
  let total = 0;
  for (let i = 0; i < k; i++) total += sales[i];
  let best = { start: 0, total };
  for (let end = k; end < sales.length; end++) {
    total += sales[end] - sales[end - k];
    if (total > best.total) best = { start: end - k + 1, total };
  }
  return best;
}

Cost: O(n) time, one addition and one subtraction per day. O(1) extra memory. Starting best from the first window, not from 0, is what makes the all-negative case right.

Exercise 4: many sales totals (medium)

Write rangeTotals(sales, queries). Each query [from, to] asks for the total sales from day from up to, but not including, day to. Return one answer per query. Start from exercises/range-totals.ts:

// Answer many "total sales from day `from` up to (not including) day `to`" questions.
// 0 <= from <= to <= sales.length. Target: O(n + q) time, q = number of queries.
export function rangeTotals(sales: number[], queries: [from: number, to: number][]): number[] {
  throw new Error("not implemented");
}

The tests check these cases:

  • an empty range
  • a list with no days
  • 100,000 queries on 100,000 days in under 200 ms

Summing each range with a loop costs O(n · q). In one run, that version passed the first two tests and failed the third with took 7173 ms.

Hint

Build before, with before[d] the total of the days before day d. How long must it be, so that to can be sales.length?

Solution
// Answer many "total sales from day `from` up to (not including) day `to`" questions.
// Prefix sums: before[d] = total of days 0..d-1. Each answer is before[to] - before[from].
// O(n + q) time, O(n) extra memory, q = number of queries.
export function rangeTotals(sales: number[], queries: [from: number, to: number][]): number[] {
  const before = new Array<number>(sales.length + 1);
  before[0] = 0;
  for (let d = 0; d < sales.length; d++) before[d + 1] = before[d] + sales[d];
  return queries.map(([from, to]) => before[to] - before[from]);
}

Cost: O(n) to build before, then O(1) per query, so O(n + q) time and O(n) extra memory. new Array(n + 1) starts holey, and that is fine here, as holey.ts showed.

Exercise 5: the longest run within a byte budget (harder)

Write longestUnderBudget(sizes, budget): the length of the longest run of consecutive requests whose sizes add up to at most budget bytes. Sizes are never negative. Start from exercises/longest-under-budget.ts:

// The longest run of consecutive requests whose total size stays within `budget` bytes.
// Sizes are never negative. Return the length of the run (0 if no single request fits).
// Target: O(n) time, O(1) extra memory.
export function longestUnderBudget(sizes: number[], budget: number): number {
  throw new Error("not implemented");
}

For [200, 100, 300, 50, 50, 400, 100] and a budget of 500, the answer is 4 (100 + 300 + 50 + 50). The tests also include requests of 0 bytes, and compare your answer with a check of every run on 100 random lists.

Hint

Use the window from longestWithFewFailures, with a total in place of the failure count. Why is it safe to drop requests from the left while the total is over budget?

Solution
// The longest run of consecutive requests whose total size stays within `budget` bytes.
// Growing window: `right` adds a request; while the window is over budget, `left` drops one.
// Each index enters and leaves the window once: O(n) time, O(1) extra memory.
// Works because sizes are never negative: dropping a request never raises the total.
export function longestUnderBudget(sizes: number[], budget: number): number {
  let left = 0;
  let total = 0;
  let best = 0;
  for (let right = 0; right < sizes.length; right++) {
    total += sizes[right];
    while (total > budget) {
      total -= sizes[left];
      left++;
    }
    best = Math.max(best, right - left + 1);
  }
  return best;
}

Cost: O(n) time, because right moves n times and left at most n times. O(1) extra memory. When a single request is over budget, left passes right and the window is empty for that step, with length 0.

Going deeper

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

Why only request times are tried as starts

busiestSlow and busiestWindow only try minutes that start at a request time. Take any minute and slide its start right to the first request inside it. No request leaves the window, so the count can’t drop, and some request-time start is always at least as busy.

A write far past the end of an array

The last line of elements-kinds.js printed DICTIONARY_ELEMENTS. Writing index 1,024 or more past the end of an array switches it to dictionary elements. V8 then keeps the elements in a hash table, a structure that finds each value by its key, instead of a row of slots.

So each read becomes a lookup in that table. The limit is JSObject::kMaxGap = 1024 in src/objects/js-objects.h. c[5] = 6 on a 3-element array only makes it holey.

Watching a string flatten

flatten.js shows flattening with another debugging function:

// Is a string stored as one flat block of characters? Plain JavaScript, because
// %StringIsFlat is a V8 debugging helper: node --allow-natives-syntax flatten.js
let s = "";
for (let i = 0; i < 5; i++) s += `req ${i}\n`;
console.log("after five +=          flat:", %StringIsFlat(s));
console.log("read s.length (" + s.length + ")    flat:", %StringIsFlat(s));
s.charCodeAt(0);
console.log("after s.charCodeAt(0)  flat:", %StringIsFlat(s));
s += "req 5\n";
console.log("after one more +=      flat:", %StringIsFlat(s));
after five +=          flat: false
read s.length (30)    flat: false
after s.charCodeAt(0)  flat: true
after one more +=      flat: false

Reading length doesn’t flatten, because every node stores its length. Reading a character does. The ConsString comment in string.h describes the cons string as a binary tree whose leaves are flat strings.

Characters and code units

A UTF-16 code unit is one 16-bit piece of text, and a string is a sequence of them, as the ECMAScript specification defines it. String indexes count code units, not characters, and an emoji takes two. "👍ok".split("") gives [ '\ud83d', '\udc4d', 'o', 'k' ], and [..."👍ok"] keeps the emoji whole, [ '👍', 'o', 'k' ]. So two pointers that reverse a string by index break an emoji in half.

Recent compiler changes for strings

As of V8 14.6 (Node.js 26, 2026), the optimizing compiler can skip building cons strings that never leave a function. The flag for this, turboshaft_string_concat_escape_analysis, is on. A separate string-builder optimization, turbo_string_builder, is off, with a note to fix and re-enable it. Both are in src/flags/flag-definitions.h.

The tables above were measured with these settings, and their growth matches the cons-string model.

Cheat sheet

Figure 10 is the summary of the module: which shape fits which sign in a problem.

sign in the problem                         shape                    cost
many re-scans of overlapping ranges         sliding window           O(n)
"longest/shortest run such that ..."        window grows, shrinks    O(n)
"every k consecutive"                       fixed window             O(n)
sorted input, find a pair                   both ends                O(n)
rewrite in place, keep or skip items        read and write           O(n)
many range totals, data does not change     prefix sums              O(n + q)

Figure 10: if the slow version re-scans a range that mostly overlaps the last one, one of these shapes removes the re-scan.

  • Two pointers: two indexes that only move forward (or inward); count their moves over the whole run, at most about 2n.
  • Sliding window, by time or by content: right adds, left drops while the window breaks the rule. Needs a rule that adding only makes worse.
  • Fixed window of k: add the item that enters, subtract the one that leaves. Only for things you can undo.
  • Both ends: sorted input and a pair: too small moves left, too large moves right.
  • Read and write: rewrite an array in place; write never passes read.
  • Prefix sums: before has n + 1 entries and before[0] = 0; [a, b) is before[b] - before[a]. Worth it for many questions on data that doesn’t change.
  • Arrays in V8: an elements kind only gets more general (except after a full fill), and holes cost nothing measurable in a plain loop.
  • Strings in V8: += builds cons strings in O(1); reading a character flattens in O(length). Don’t read inside the append loop.
  • Next: Module 3 looks inside the hash table behind Map and Set, and finds a duplicate order without a loop over all earlier orders.

Sources