Sliding Window Maximum
Compute the maximum of every fixed-size window in O(n) using a monotonic deque, with clear handling of invalid sizes.
Code
export function slidingWindowMaximum(values, size) {
if (!Array.isArray(values)) throw new TypeError("values must be an array");
if (!Number.isInteger(size) || size <= 0) {
throw new RangeError("size must be a positive integer");
}
if (size > values.length) return [];
const result = [];
const deque = [];
let head = 0;
for (let index = 0; index < values.length; index += 1) {
while (head < deque.length && deque[head] <= index - size) head += 1;
while (deque.length > head && values[deque[deque.length - 1]] <= values[index]) {
deque.pop();
}
deque.push(index);
if (index >= size - 1) result.push(values[deque[head]]);
}
return result;
}
export function maxInEachWindow(values, size) {
return slidingWindowMaximum(values, size);
}How the snippet works
The working surface is the functions slidingWindowMaximum and maxInEachWindow — everything else is wiring.
The structure is a loop within a loop: for (let index = 0; index < values.length; index += 1) outside, while (head < deque.length && deque[head] <= index - size) head += 1; inside. A guard precedes the TypeError and RangeError: bad state stops the flow there instead of continuing.
A fresh value is allocated for the result; the arguments stay untouched.
Points of care
- The guard
size > values.lengthshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The main signature reads export function slidingWindowMaximum(values, size)
Import slidingWindowMaximum from the file and call it — the rest of the code is implementation detail.
Statements that matter
if (!Array.isArray(values)) throw new TypeError("values must be an array");
while (head < deque.length && deque[head] <= index - size) head += 1;
throw new RangeError("size must be a positive integer");
Interactive Tools for This Topic
FAQ
- Does `slidingWindowMaximum` modify its input?
- No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
- What does the snippet do with malformed data?
- It throws `TypeError` and `RangeError` before any real work runs, via the guard `size > values.length` — handle it at the call site or let it propagate deliberately.
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `slidingWindowMaximum`, `maxInEachWindow` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.