Full answer
The naive solution scans each window of k elements for the maximum: O(n times k). A heap gives O(n log n) but needs lazy deletion of items that leave the window. A monotonic deque does it in O(n).
Idea: maintain a double-ended queue of indexes such that the values at those indexes are strictly decreasing from front to back. The front always holds the index of the current maximum.
For each index i:
- Remove from the back while
a[back] <= a[i]. Those elements can never be the maximum of any window that includesi, becausea[i]is at least as large and stays in the window longer. - Push
iat the back. - If the front index is
i - kor older, remove it, because it left the window. - Once
i >= k - 1, the first full window is complete, so recorda[front].
Why it is O(n): every index is pushed once and removed at most once, from the back or the front. So the total work over all steps is at most 2n operations.
In JavaScript there is no built-in deque. Array.prototype.shift is O(n) in the worst case, so a long input could be slow. Use an index pointer (head) into an array and advance it instead of shifting, as the snippet does. Or implement a small ring buffer.
The same monotonic queue pattern solves the shortest subarray with a given sum and constrained dynamic programming problems. A monotonic stack, which is the same idea with one end, solves "next greater element" and "largest rectangle in a histogram".
Edge cases: k equal to 1, k equal to the array length, k larger than the array, and equal values, which is why the comparison uses <=.
function slidingWindowMax(a, k) {
if (!Number.isInteger(k) || k < 1 || k > a.length) return [];
const deque = []; // indexes, values decreasing
let head = 0; // front of the deque, advanced instead of calling shift
const result = [];
for (let i = 0; i < a.length; i++) {
while (deque.length > head && a[deque[deque.length - 1]] <= a[i]) deque.pop();
deque.push(i);
if (deque[head] <= i - k) head++;
if (i >= k - 1) result.push(a[deque[head]]);
}
return result;
}
function naive(a, k) {
const out = [];
for (let i = 0; i + k <= a.length; i++) out.push(Math.max(...a.slice(i, i + k)));
return out;
}
console.log(slidingWindowMax([1, 3, -1, -3, 5, 3, 6, 7], 3));
console.log(slidingWindowMax([9, 8, 7, 6], 2), slidingWindowMax([1, 2, 3, 4], 4), slidingWindowMax([5], 1));
console.log(slidingWindowMax([2, 2, 2], 2), slidingWindowMax([1, 2], 3));
// compare with the naive version on pseudo-random data (seeded generator, same every run)
let seed = 12345;
const random = () => ((seed = (seed * 1664525 + 1013904223) % 4294967296) / 4294967296);
let allMatch = true;
for (let round = 0; round < 200; round++) {
const data = Array.from({ length: 1 + Math.floor(random() * 30) }, () => Math.floor(random() * 20) - 10);
const k = 1 + Math.floor(random() * data.length);
if (JSON.stringify(slidingWindowMax(data, k)) !== JSON.stringify(naive(data, k))) allMatch = false;
}
console.log('matches the naive version on 200 random cases:', allMatch);Run with Node.js v24.22.1 as js-116.js; two runs gave identical output. Output: [ 3, 3, 5, 5, 6, 7 ] [ 9, 8, 7 ] [ 4 ] [ 5 ] [ 2, 2 ] [] matches the naive version on 200 random cases: true
Key points
- Keep a deque of indexes with decreasing values; the front is the window maximum.
- Pop from the back while values are not larger than the new value; pop the front when its index leaves the window.
- Each index enters and leaves once, so the time is O(n).
- Array shift is slow; use a head pointer or a ring buffer.
- The pattern also gives next greater element and histogram solutions with a monotonic stack.
Common mistakes
- Using strict less-than when popping from the back, which keeps equal values and wastes work.
- Storing values and not indexes, so there is no way to tell when an element left the window.
- Calling shift in a loop on large inputs.
- Recording results before the first full window is complete.
Follow-ups
- How does a monotonic stack solve next greater element?
- How would you solve this with a heap, and what is the cost?
- How would you implement an O(1) deque in JavaScript?
Tips
- Explain why dropping smaller elements from the back is safe.
- State the amortized argument: each index enters and leaves once.
- Mention that Array shift is a performance trap.