Sliding Window Maximum
LeetCode 239 · Hard · solution, intuition & step-by-step walkthrough
Monotonic decreasing deque; front = window max.
This is how I solved Sliding Window Maximum (LeetCode 239), a hard problem from the Monotonic Queue pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Keep a deque of indices whose values are decreasing from front to back. The front is always the maximum of the current window. A new value evicts smaller values from the back (they can never be a max again), and indices that slid out of the window leave from the front.
Approach
- 1
Pop expired indices from the front.
- 2
Pop indices with smaller or equal values from the back.
- 3
Append the current index.
- 4
Once the first window is full, record nums[dq[0]].
How I solved it
Monotonic dequePythonO(n) time · O(k) space
class Solution:
def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
#monotonic deque
"""
nums = [1,3,-1,-3,5,3,6,7], k = 3
monotonically decreasing deque
front back
a) Remove indices from front if these are expired or outside the current window
b) Remove indices from back if their corresponding values are smaller or eqaul to the current element
c) front = always contains the candidate maximum
d) back = candidate may be removed because a larger element arrivec
"""
result=[]
dq = deque([])
n = len(nums)
for i in range(n):
#expired/out of window items remove from front
while dq and dq[0]<=i-k:
dq.popleft()
#Remove indices from back if their corresponding values are smaller or eqaul to the current element
while dq and nums[dq[-1]]<=nums[i]:
dq.pop()
dq.append(i)
#window is complete
if i>=k-1:
#keep the candidate maximum
result.append(nums[dq[0]])
return resultSliding Window Maximum — FAQ
What is the intuition behind Sliding Window Maximum?
Keep a deque of indices whose values are decreasing from front to back. The front is always the maximum of the current window. A new value evicts smaller values from the back (they can never be a max again), and indices that slid out of the window leave from the front.
How do you solve Sliding Window Maximum (LeetCode 239)?
1. Pop expired indices from the front. 2. Pop indices with smaller or equal values from the back. 3. Append the current index. 4. Once the first window is full, record nums[dq[0]].
What is the time and space complexity of Sliding Window Maximum?
Time: O(n). Space: O(k). (Accepted approach: Monotonic deque.)
What are common mistakes in Sliding Window Maximum?
Store indices, not values — you need them to expire elements.