Sliding Window Maximum

Max of every length-k window via a monotonic deque.

Hard
Time O(n) Space O(k)
LeetCode
3 min read
sliding-window monotonic-deque array

Problem#

Given nums and k, return an array of the maximum of every length-k window.

Examples#

  • nums = [1,3,-1,-3,5,3,6,7], k = 3[3,3,5,5,6,7]
  • nums = [1], k = 1[1]

Constraints#

  • 1 <= nums.length <= 10^5, 1 <= k <= nums.length.

Hints#

Hint 1
Maintain indices of candidates in a deque, sorted by value descending. The front is always the current max.

Approach#

Monotonic deque storing indices. Before pushing i, pop indices with values ≤ nums[i] from the back (they’re dominated). Pop from the front if the index falls outside the window. The front is the answer for each window.

Solution#

Sliding Window Maximum
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
deque<int> dq;
vector<int> ans;
ans.reserve(nums.size() - k + 1);
for (int i = 0; i < (int)nums.size(); ++i) {
while (!dq.empty() && nums[dq.back()] <= nums[i]) dq.pop_back();
dq.push_back(i);
if (dq.front() <= i - k) dq.pop_front();
if (i >= k - 1) ans.push_back(nums[dq.front()]);
}
return ans;
}
};

Editorial#

Each index enters and leaves the deque exactly once → O(n). The deque encodes a monotonically decreasing sequence of candidates; smaller values that arrive after a larger value are useless once the larger value is still in the window (the larger one will be picked first). Front-stale check ensures the max actually lies within the current window.

Complexity#

  • Time: O(n).
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.