Maintain a monotonic deque to report every window maximum.
Return the maximum for each window of k consecutive elements. As the window moves one step, one value enters and another expires.
Track maximum candidates in a deque
A deque (double-ended queue) lets you remove candidates from either end. Remove indices that leave the window and candidates that can no longer become a maximum.
Submit your implementation when it passes the examples.
Given an integer array and a window size k, return the maximum value in every contiguous window of size k.
Process the array efficiently without scanning every window from scratch.
1 ≤ k ≤ nums.length ≤ 100,000-10,000 ≤ nums[i] ≤ 10,000Results appear here after a run.
Store indices in increasing order from front to back. Their values must strictly decrease in that direction. With current index i, first remove indices at the front that are at most i - k. Next remove indices at the back whose values are at most nums[i]. The newer value is at least as large and stays in the window longer. Append i. Once the window is full, read the value at the front index.
For [4, 2, 3, 1] with k = 3, the arrival of 3 discards the older 2. The candidates are now indices [0, 2] with values [4, 3], so the first maximum is 4. On the next step, index 0 expires. The candidates become [2, 3], with values [3, 1], so the second maximum is 3.
function maxSlidingWindow(nums, k) {
const entries = {};
let front = 0;
let back = 0;
const result = [];
for (let index = 0; index < nums.length; index++) {
while (front < back && entries[front] <= index - k) {
delete entries[front];
front++;
}
while (
front < back &&
nums[entries[back - 1]] <= nums[index]
) {
back--;
delete entries[back];
}
entries[back] = index;
back++;
if (index >= k - 1) {
result.push(nums[entries[front]]);
}
}
return result;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Each index enters and leaves the deque at most once. |
| Auxiliary space | O(k) | At most k candidate indices are live. The returned array separately holds n - k + 1 maxima. |