Sliding Window Maximum
Given an array of integers nums and a window size k, slide a window of k numbers from the left end of the array to the right end, one position at a time. Return the largest number in each window.
Example 1
Input: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3 Output: [3, 3, 5, 5, 6, 7]
The windows are [1, 3, -1], [3, -1, -3], [-1, -3, 5], [-3, 5, 3], [5, 3, 6] and [3, 6, 7].
Example 2
Input: nums = [1], k = 1 Output: [1]
Constraints
1 <= k <= nums.length <= 100000-10000 <= nums[i] <= 10000
Approach
Scanning each window for its maximum takes O(n · k) time. The fix comes from noticing which numbers matter. When a new number enters the window, any smaller number before it can never be a maximum again: the new number is larger and will stay in the window longer. So those smaller numbers can be thrown away.
Keep a double-ended queue of indexes whose values decrease from front to back. When a number arrives, pop smaller or equal values off the back, then push its index. If the index at the front has slid out of the window, pop it from the front. Once the first full window is in place, the value at the front of the queue is the window's maximum. Storing indexes rather than values is what lets you tell when the front has left the window.
Steps
- Create an empty double-ended queue of indexes and an empty result list.
- For each index
i, pop indexes off the back while their values are<= nums[i], then pushi. - If the front index is
<= i - k, pop it from the front. - Once
i >= k - 1, appendnums[front]to the result. Return the result.
from collections import deque
from typing import List
def max_sliding_window(nums: List[int], k: int) -> List[int]:
window = deque() # indexes whose values decrease from front to back
result = []
for i, num in enumerate(nums):
while window and nums[window[-1]] <= num:
window.pop() # smaller values can never be a maximum again
window.append(i)
if window[0] <= i - k:
window.popleft() # the front index has slid out of the window
if i >= k - 1:
result.append(nums[window[0]])
return resultComplexity
- Time:
O(n). Each index is pushed once and popped at most once. - Space:
O(k)for the queue, which never holds more than one window of indexes.
Common mistakes
- Storing values instead of indexes. You then can't tell when the maximum has left the window.
- Using a heap without removing values that have left the window. The top of the heap can then be a number from an earlier window.
- Recording results before the first window is full, which adds
k - 1extra values at the start.