Emmanuel Akinfulubi

JavaScriptArray

Sliding window maximum in JavaScript

Advanced · 5 min read

A sliding window is a fixed-size stretch of a list that moves along one step at a time. With a window of 3 over [1, 3, -1, -3, 5, 3, 6, 7], you look at 1, 3, -1, then 3, -1, -3, and so on. Asking for the biggest value in each window gives [3, 3, 5, 5, 6, 7]. Charts do this to show "the highest price in the last 7 days" for every day.

In this tutorial you will first write the obvious version, which re-reads every window. Then you will build a faster one that walks the list once. We will trace it by hand as we go. You should know arrays, for loops, while loops and Math.max.

The windows, by hand

A list of 8 values with a window of 3 has 8 - 3 + 1 = 6 windows:

Output

[ 1,  3, -1]  -> 3
[ 3, -1, -3]  -> 3
[-1, -3,  5]  -> 5
[-3,  5,  3]  -> 5
[ 5,  3,  6]  -> 6
[ 3,  6,  7]  -> 7

Neighboring windows share most of their values. The obvious version ignores that and starts each window from scratch.

The key idea: values that can never win

Look at the window 3, -1, -3, and imagine 5 arrives next. From now on, 3, -1 and -3 are all older than 5 and smaller than it. Every future window that still contains them also contains 5, so none of them can ever be the maximum again. You can throw them away for good.

If you always throw such values away, the ones you keep are in decreasing order: each kept value is smaller than the one before it. The front of that list is the biggest, which is the answer for the current window.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

53 The maximum of every sliding window

hard

For [1, 3, -1, -3, 5, 3, 6, 7] and a window of 3, report the maximum of each window: [3, 3, 5, 5, 6, 7]. Do it without re-scanning each window.

Stuck? Three hints, smallest first
  1. 1. The obvious answer calls Math.max on every window, which is O(n·k). Start there, then improve it.
  2. 2. Keep a list of indexes whose values are in decreasing order; the front is the current maximum.
  3. 3. Before adding an index, drop every index at the back whose value is no larger — it can never be a maximum again.

Step 1: the obvious version

Step 1

const windowMaxNaive = (xs, k) =>
  Array.from({ length: Math.max(0, xs.length - k + 1) }, (_, i) => Math.max(...xs.slice(i, i + k)));

console.log(windowMaxNaive([1, 3, -1, -3, 5, 3, 6, 7], 3)); // [ 3, 3, 5, 5, 6, 7 ]
console.log(windowMaxNaive([1, 2], 5));                     // []

Array.from({ length: n }, fn) makes an array of n items, calling fn with each index i. Here n is the number of windows. Each item takes the slice of k values starting at i and spreads it into Math.max. Math.max(0, ...) keeps the count from going negative when the window is longer than the list.

This is correct and easy to read, but it reads all k values again for every window. Keep it anyway: it is the yardstick to check the fast one against.

Step 2: keep indexes, not values

The fast version keeps a list called window. It stores indexes into xs, not the values themselves, because we need to know when a value has slid out of the window, and its index tells us that.

For each new index i, before adding it, remove indexes from the back whose values are no bigger than xs[i]. Those are the values that can never win:

Step 2

const xs = [1, 3, -1, -3, 5];
const window = [];

for (let i = 0; i < xs.length; i++) {
  while (window.length > 0 && xs[window.at(-1)] <= xs[i]) window.pop();
  window.push(i);
  console.log(i, window.map((j) => xs[j]));
}
// 0 [ 1 ]
// 1 [ 3 ]
// 2 [ 3, -1 ]
// 3 [ 3, -1, -3 ]
// 4 [ 5 ]

The printout shows the values for each kept index. When 3 arrives, it removes 1. -1 and -3 are smaller, so they stay behind 3. When 5 arrives, it clears out all three. The kept values always go down from front to back.

Step 3: drop the front when it slides out

The front is the biggest value, but it might be too old. The window covering index i starts at i - k + 1. So if the front index is i - k or less, it has slid out and must go:

Step 3

const xs = [5, 1, 2, 3];
const k = 2;
const window = [];

for (let i = 0; i < xs.length; i++) {
  while (window.length > 0 && xs[window.at(-1)] <= xs[i]) window.pop();
  window.push(i);
  if (window[0] <= i - k) window.shift();
  console.log(i, window.map((j) => xs[j]));
}
// 0 [ 5 ]
// 1 [ 5, 1 ]
// 2 [ 2 ]
// 3 [ 3 ]

At i = 2 the window covers indexes 1 and 2. The front is still index 0, the 5, which is i - k, so it is dropped. In the printout, 2 had already removed 1 from the back, leaving just 2. Without this check, 5 would wrongly be reported as the maximum of 1, 2.

Step 4: report the answer

Once the first full window is in place, at i = k - 1, every step has an answer: the value at the front.

Step 4

function windowMax(xs, k) {
  if (!Number.isInteger(k) || k < 1) throw new RangeError('k must be a positive integer');
  const out = [];
  const window = [];
  let removals = 0;

  for (let i = 0; i < xs.length; i++) {
    while (window.length > 0 && xs[window.at(-1)] <= xs[i]) { window.pop(); removals++; }
    window.push(i);
    if (window[0] <= i - k) { window.shift(); removals++; }
    if (i >= k - 1) out.push(xs[window[0]]);
  }
  return { values: out, removals };
}

const xs = [1, 3, -1, -3, 5, 3, 6, 7];
console.log(windowMax(xs, 3).values);      // [ 3, 3, 5, 5, 6, 7 ]
console.log(windowMax(xs, 1).values);      // [ 1, 3, -1, -3, 5, 3, 6, 7 ]
console.log(windowMax([2, 2, 2], 2).values); // [ 2, 2 ]
console.log(windowMax([1, 2], 5).values);  // []
console.log(windowMax(xs, 3).removals);    // 7

The first line of the function refuses a window size that isn't a whole number of at least 1. A window of 0 makes no sense. Without the check, windowMax([1, 3, -1], 0) would return three undefined values instead of an error.

Step 5: why it's fast

There is a while loop inside a for loop, which usually suggests slow code. Here it isn't. Every index is pushed once and can be removed at most once, from the back or from the front. So the total number of removals can never be more than the length of the list. The removals counter shows it: 7 removals for 8 values.

Try a bigger list to see the gap. The naive version reads k values for every window, so you can work out its reads with one multiplication:

Step 5

function windowMax(xs, k) {
  if (!Number.isInteger(k) || k < 1) throw new RangeError('k must be a positive integer');
  const out = [];
  const window = [];
  let removals = 0;
  for (let i = 0; i < xs.length; i++) {
    while (window.length > 0 && xs[window.at(-1)] <= xs[i]) { window.pop(); removals++; }
    window.push(i);
    if (window[0] <= i - k) { window.shift(); removals++; }
    if (i >= k - 1) out.push(xs[window[0]]);
  }
  return { values: out, removals };
}

const big = Array.from({ length: 10000 }, (_, i) => (i * 7919) % 10007);
const k = 1000;
console.log((big.length - k + 1) * k);   // 9001000
console.log(windowMax(big, k).removals); // 9990

With a window of 1,000, the naive version reads about nine million values. The fast one removes fewer than 10,000 indexes in total, which stays below the length of the list, however big k gets. For small windows the difference is tiny, and the naive version is perfectly good there.

The full solution

The panel has both versions. It prints every window of 3 with its maximum, then the fast and naive results side by side, the removal count, and what happens with a window of 0. Press Run and check the two results agree.

The answer

// The obvious version: correct, and it re-reads every window.
const windowMaxNaive = (xs, k) =>
  Array.from({ length: Math.max(0, xs.length - k + 1) }, (_, i) => Math.max(...xs.slice(i, i + k)));

// One pass. `window` holds indexes whose values decrease from front to back.
function windowMax(xs, k) {
  if (!Number.isInteger(k) || k < 1) throw new RangeError('k must be a positive integer');
  const out = [];
  const window = [];
  let removals = 0;

  for (let i = 0; i < xs.length; i++) {
    while (window.length > 0 && xs[window.at(-1)] <= xs[i]) { window.pop(); removals++; }
    window.push(i);
    if (window[0] <= i - k) { window.shift(); removals++; }   // the front fell out of range
    if (i >= k - 1) out.push(xs[window[0]]);
  }
  return { values: out, removals };
}

const xs = [1, 3, -1, -3, 5, 3, 6, 7];

const refused = (() => {
  try { windowMax(xs, 0); return 'no error'; } catch (e) { return e.constructor.name; }
})();

console.log('input      :', xs);
console.log('windows of 3, one per line:');
for (let i = 0; i + 3 <= xs.length; i++) console.log('  ', xs.slice(i, i + 3), '->', Math.max(...xs.slice(i, i + 3)));
console.log('windowMax  :', windowMax(xs, 3).values);
console.log('naive      :', windowMaxNaive(xs, 3));
console.log('removals   :', windowMax(xs, 3).removals, 'for', xs.length, 'elements');
console.log('k of 0     :', refused);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test("the classic example", windowMax(xs, 3).values, [3, 3, 5, 5, 6, 7]);
test('the naive version agrees', windowMax(xs, 3).values, windowMaxNaive(xs, 3));
test('there are n - k + 1 windows', windowMax(xs, 3).values.length, xs.length - 3 + 1);
test('a window of 1 is the list itself', windowMax(xs, 1).values, xs);
test('a window as long as the list gives one answer', windowMax([1, 2, 3], 3).values, [3]);
test('a window longer than the list gives none', windowMax([1, 2], 5).values, []);
test('duplicates are handled', windowMax([2, 2, 2], 2).values, [2, 2]);
test('each index leaves the window at most once, so the work is linear', windowMax(xs, 3).removals <= xs.length, true);
test('a window of 0 is refused rather than looping', refused, 'RangeError');

The insight is about what can be thrown away. If a new value is at least as large as the value at the back of the window, that older value can never be the maximum of any window containing the new one — so it is discarded immediately and permanently. What remains is a decreasing list of candidates whose front is always the answer.

The removals count is the proof that this is linear rather than quadratic: every index enters the window once and leaves at most once, so the total work is bounded by the length of the input, even though there is a while loop inside a for loop. Counting the discards is a good habit for any algorithm whose cost argument is amortised — it turns "trust me, it is O(n)" into something a test can check.

The naive version is kept because it is the specification. It is obviously correct, it is the right choice for small windows, and it is what the fast version is checked against.

Common mistakes

  • Storing values instead of indexes. You can't tell when a value has slid out of the window. Store indexes and read the values through them.
  • Using < instead of <= when clearing the back. It still gives the right answer, but equal values pile up in window for no reason. <= lets the newer copy replace the older one.
  • Reporting before the first window is full. Only push an answer once i >= k - 1.

Try it yourself

  1. Change windowMax into windowMin. (Hint: flip one comparison.)
  2. Use the naive version to check the fast one on 100 random lists.
  3. Write the sum of every window of k values in one pass: add the new value and subtract the one that slid out.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.