Sliding Window Maximum

Problem

Given an integer array nums and an integer k, return an array of the maximum values of each sliding window of size k moving from left to right across nums.

  • 1 ≤ nums.length ≤ 10⁵
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • 1 ≤ k ≤ nums.length

Example

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]

The brute-force approach would compute the maximum for each window by scanning all k elements, resulting in O(n*k) time. Instead, the algorithm maintains a deque of indices representing elements in decreasing order of their values. For each new element at index r, it removes indices from the deque's tail whose corresponding values are less than nums[r], ensuring the deque's head always holds the index of the maximum element in the current window. When the left pointer l moves past the deque's head, that index is removed. Once the window size reaches k, the maximum (nums[q[0]]) is appended to the output. This approach achieves O(n) time by ensuring each element is added and removed at most once.

Approach

Straightforward Solution

A naive solution iterates over each window and scans all k elements to find the maximum, resulting in O(n*k) time, which is too slow for large inputs.

Core Observation

The maximum of a sliding window depends on the relative order of elements within that window. Maintaining a data structure that preserves the order of potential maximum candidates allows efficient updates as the window slides.

Path to Optimal

The key recognition signals are 'sliding window', 'maximum in each window', and 'efficient updates'. These indicate the Sliding Window pattern combined with a Monotonic Queue (deque) because it allows constant-time retrieval of the maximum while efficiently discarding obsolete or smaller elements as the window moves.

Optimal Approach

Use a deque to store indices of elements in decreasing order of their values. For each new element, pop from the deque's tail while the current element is greater, ensuring the deque's head is always the maximum. Remove the head if it falls out of the window. Append the maximum to the output once the window size reaches k. This guarantees O(n) time complexity.

Time

O(n)

Each element is added to and removed from the deque at most once, resulting in linear time relative to the input size.

Space

O(k)

The deque stores at most k indices corresponding to elements in the current window, so auxiliary space scales linearly with the window size.

Pattern Spotlight

Sliding Window (Monotonic Queue)

Maintain a deque of indices in decreasing order of their values to ensure the front always holds the maximum for the current window, discarding smaller elements as new ones arrive and removing indices that fall out of the window.

Solution

1import collections
2
3class Solution:
4 def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
5 output = []
6 q = collections.deque()
7 l = r = 0
8
9 while r < len(nums):
10 while q and nums[q[-1]] < nums[r]:
11 q.pop()
12 q.append(r)
13
14 if l > q[0]:
15 q.popleft()
16
17 if (r + 1) >= k:
18 output.append(nums[q[0]])
19 l += 1
20 r += 1
21
22 return output

Step-by-Step Solution

1

Initialize Output List, Deque, and Window Pointers

5output = []
6q = collections.deque()
7l = r = 0

Objective

To prepare data structures and pointers for tracking the sliding window and its maximum efficiently.

Key Insight

Initializing an empty output list collects the maximums for each window. The deque will store indices of elements in decreasing order of their values, enabling O(1) access to the current maximum. Two pointers, l and r, represent the left and right boundaries of the sliding window, facilitating window movement and boundary checks.

Interview Quick-Check

Core Logic

The deque stores indices, not values, to efficiently check if elements are out of the current window and to access their values in nums.

State & Boundaries

Both pointers start at 0, representing an empty window that will expand as r moves forward.

2

Expand Window and Maintain Monotonic Deque

9while r < len(nums):
10 while q and nums[q[-1]] < nums[r]:
11 q.pop()
12 q.append(r)

Objective

To slide the right pointer forward, updating the deque to maintain decreasing order of values and removing indices of smaller elements.

Key Insight

As the window expands by moving r, the algorithm removes from the deque's tail all indices whose corresponding values are less than nums[r]. This ensures the deque remains sorted in decreasing order, so the front always holds the maximum. This step is crucial to avoid scanning the entire window for the maximum and to maintain O(n) complexity by ensuring each element is processed once.

Interview Quick-Check

Core Logic

Removing smaller elements from the deque's tail before appending the current index ensures the deque's head is always the maximum for the current window.

Common Pitfalls & Bugs

Failing to remove smaller elements leads to incorrect maximums and degrades performance to O(n*k).

Complexity

Each element is pushed and popped at most once, guaranteeing linear time complexity.

3

Remove Out-of-Window Indices from Deque Head

14if l > q[0]:
15 q.popleft()

Objective

To discard indices from the deque's front that are no longer within the current sliding window boundaries.

Key Insight

When the left pointer l moves past the index at the deque's front, that index is removed because it no longer belongs to the current window. This step ensures the deque only contains indices relevant to the current window, maintaining correctness of the maximum retrieval.

Interview Quick-Check

Core Logic

Removing indices outside the window from the deque's front keeps the maximum candidate valid for the current window.

State & Boundaries

The condition l > q[0] checks if the oldest index is out of the window.

4

Record Maximum and Slide Window Forward

17if (r + 1) >= k:
18 output.append(nums[q[0]])
19 l += 1
20r += 1

Objective

To append the current window's maximum to the output once the window size reaches k and then move the left pointer to slide the window.

Key Insight

Once the window size is at least k, the maximum element is at the deque's front. Appending nums[q[0]] to output captures this maximum. Incrementing l slides the window forward, preparing for the next maximum calculation. Incrementing r continues expanding the window until the end of the array.

Interview Quick-Check

Core Logic

Appending nums[q[0]] after the window reaches size k ensures the output contains the maximum for each valid window.

State & Boundaries

The condition (r + 1) >= k ensures the window is fully formed before recording maximums.

Common Pitfalls & Bugs

Forgetting to increment l after recording the maximum would cause incorrect window boundaries and output.

5

Return the List of Sliding Window Maximums

22return output

Objective

To output the collected maximum values for all sliding windows after processing the entire array.

Key Insight

Returning the output list completes the algorithm, providing the required maximums for each window in order. This final step is straightforward but essential for correctness.

Interview Quick-Check

Core Logic

Returning the output list delivers the final result of the sliding window maximum computation.

Line Analysis

This solution has 2 Critical lines interviewers watch for.

Line 10 Critical
while q and nums[q[-1]] < nums[r]:

While the deque is not empty and the current element is greater than the element at the deque's tail, pop from the tail.

Removing smaller elements from the tail maintains the deque's decreasing order, ensuring the front always holds the maximum candidate for the current window.

Line 18 Critical
output.append(nums[q[0]])

Append the value at the deque's front index to the output list as the current window's maximum.

The deque's front always holds the index of the maximum element in the current window, so appending nums[q[0]] records the correct maximum.

Line 6 Core
q = collections.deque()

Create a deque to store indices of elements in decreasing order of their values.

The deque enables O(1) access to the current maximum and efficient updates by maintaining a monotonic decreasing order of values via indices.

Line 14 Core
if l > q[0]:

Check if the left pointer has moved past the deque's front index.

This condition detects when the maximum candidate at the deque's front is no longer in the current window and must be removed.

Line 15 Core
q.popleft()

Remove the front index from the deque if it is out of the current window.

Removing outdated indices keeps the deque relevant to the current window, ensuring correctness of the maximum retrieval.

Line 11 Core
q.pop()

Pop the last index from the deque.

This operation discards indices of elements smaller than the current element, preserving the monotonic property of the deque.

Line 12 Core
q.append(r)

Append the current index r to the deque.

Adding the current index ensures the deque contains all potential maximum candidates for the current and future windows.

Line 17 Core
if (r + 1) >= k:

Check if the window size has reached at least k elements.

This condition ensures that maximums are only recorded once the window is fully formed, preventing premature output.

Line 19 Core
l += 1

Increment the left pointer to slide the window forward.

Moving the left pointer advances the window, preparing for the next maximum calculation and ensuring the window size remains constant.

Line 9 Standard
while r < len(nums):

Start a loop to expand the right pointer until it reaches the end of nums.

This loop iterates over each element, progressively expanding the sliding window and updating the deque accordingly.

Line 20 Standard
r += 1

Increment the right pointer to continue expanding the window.

Advancing the right pointer progresses the iteration through the array, allowing the window to slide across all elements.

Line 7 Standard
l = r = 0

Initialize left and right pointers to zero, representing the sliding window boundaries.

These pointers track the current window's start and end positions, enabling controlled window movement across the array.

Line 22 Standard
return output

Return the list of maximum values for all sliding windows.

This final step outputs the computed maximums, completing the problem's requirement.

Line 5 Basic
output = []

Initialize an empty list to store the maximums of each sliding window.

This list accumulates the results as the window slides, ensuring the final output contains all maximum values in order.

Test Your Understanding

Why does maintaining a deque of indices in decreasing order of their values guarantee O(n) time complexity?

Because each element is pushed and popped at most once from the deque, ensuring that all operations across the entire array sum to O(n), avoiding repeated scanning of elements.

Related Problems

Sliding Window pattern

Don't just read it. Drill it.

Reconstruct Sliding Window Maximum from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Sliding Window Maximum drill

or drill a free problem