Sliding Window Maximum
Report the maximum of every window of size k in O(n), with a deque of candidate indices.
The problem
You get an integer array nums and a window size k. A window covering k consecutive elements slides from the left end of the array to the right end, one step at a time. Return an array with the maximum of each window, in order.
Input nums = [4, 2, 12, 3, 8, 1, 6], k = 3
Output [12, 12, 12, 8, 8]
12 stays the maximum while it is inside the window; once it leaves, 8 takes over.
Input nums = [5, -1], k = 1
Output [5, -1]
With k = 1 every element is its own window.
Key constraint: Up to 100,000 numbers, and k can be as large as the array, so rescanning each window (O(n * k)) is too slow.
How to spot the pattern
- You need the maximum (or minimum) of every window of a fixed size.
- A number that is smaller than a newer number can never be a window maximum again, so it can be thrown away.
The idea
Keep a deque of indices whose values decrease from front to back, so the front is always the current window's maximum. When a new number arrives, pop the numbers at the back that are not bigger than it: the new one is at least as large and stays in the window longer, so they can never be a maximum again. Also drop the front index once it slides out of the window.
Brute force: Scan each of the n - k + 1 windows for its maximum, which takes O(n * k) time.
Step by step
- 1Create an empty deque of indices and an empty result list.
- 2For each index
i, pop indices from the back while their values are less than or equal tonums[i], then pushi. - 3If the index at the front is
i - kor smaller, it has left the window, so pop it from the front. - 4Once
i >= k - 1, appendnums[front]to the result. - 5Return the result.
See the pattern move
The sliding window pattern on a small example. Step through it, or press play.
Code
from collections import deque
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
dq = deque() # indices; their values decrease from front to back
result = []
for i, num in enumerate(nums):
while dq and nums[dq[-1]] <= num:
dq.pop() # smaller values can never be a maximum again
dq.append(i)
if dq[0] <= i - k:
dq.popleft() # the front has slid out of the window
if i >= k - 1:
result.append(nums[dq[0]])
return resultComplexity
Time
O(n)
Space
O(k)
Each index is pushed once and popped at most once, so all the deque work adds up to O(n); the deque never holds more than k indices, and the output array is not counted.
Watch out for
- Storing values instead of indices in the deque, which makes it impossible to tell when the front has left the window.
- Checking the left edge with the wrong bound: the front is outside the window when its index is
<= i - k. - Recording a maximum before the first window is complete; results start only at
i = k - 1.
Follow-up questions
Could a heap work instead?
Yes: push (value, index) pairs into a max-heap and, before reading the top, pop entries whose index has already left the window. That is O(n log n), easier to come up with but slower than the deque.
How would you get the minimum of every window?
Flip the comparison so the deque keeps values in increasing order; the front is then the minimum. The same deque idea is the monotonic stack from Daily Temperatures, with removals at the front as well.
In Hinglish
Deque mein sirf kaam ke indices rakho: naya bada number aaye toh peeche ke chhote nikaal do, aur jo window se bahar ho gaya use aage se hatao.