Sliding Window Maximum
Difficulty: Hard · Pattern: Sliding Window · LeetCode #239
A window of size k slides from the left of nums to the right, one position at a time. Return a list with the maximum of each window position.
Example
text
nums = [4, 2, 12, 3, 8, 1, 7], k = 3
windows: [4,2,12] [2,12,3] [12,3,8] [3,8,1] [8,1,7]
→ [12, 12, 12, 8, 8]Hints
- A heap gives O(n log n). Can you get O(n)?
- If a newer element is larger than an older one, the older one can never be a window max again.
- Keep a deque of indices whose values are decreasing; the front is the current max.
Approach
Maintain a deque of indices with strictly decreasing values:
- Before pushing index
i, pop from the back every index whose value ≤nums[i], since they're dominated forever. - Pop from the front if that index has slid out of the window (
≤ i − k). - Once
i ≥ k − 1, the front holds the window's max.
Every index is pushed and popped at most once, so O(n).
Complexity
Time: O(n). Space: O(k) for the deque.
Python solution
from collections import deque
def maxSlidingWindow(nums, k):
dq, out = deque(), []
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop()
dq.append(i)
if dq[0] <= i - k:
dq.popleft()
if i >= k - 1:
out.append(nums[dq[0]])
return outJavaScript solution
function maxSlidingWindow(nums, k) {
const dq = []; let head = 0; const out = []; // array + head pointer as a deque
for (let i = 0; i < nums.length; i++) {
while (dq.length > head && nums[dq[dq.length - 1]] <= nums[i]) dq.pop();
dq.push(i);
if (dq[head] <= i - k) head++;
if (i >= k - 1) out.push(nums[dq[head]]);
}
return out;
}