#239

Sliding Window Maximum

Hard Monotonic deque

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

For every window of size k sliding across the array, return the maximum.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the maximum of every window of size k.

Why this works: a deque of indexes with decreasing values. The front is the max; drop it when it leaves the window, and drop smaller values from the back.

Example: [1, 3, -1, -3, 5, 3, 6, 7], k = 3

maxima: 3, 3, 5, 5, 6, 7

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Storing values instead of indexes, so you can't tell when the front has left the window.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(k).
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon