← Back to Algorithms, page 2

algorithms-0026 · Hard senior

Sliding window maximum: return the maximum of every window of size k as it slides across a list.

Keep a deque of indices whose values are strictly decreasing from front to back. When a new value arrives, pop smaller or equal values from the back, since they can never be a maximum while the new value is in the window; pop the front if it has left the window. The front is always the current maximum. Each index is pushed and popped at most once, so the total is O(n).

Full answer

Problem

Given nums and k, return a list of the maximum value in each window nums[i:i + k].

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

Constraints: 1 <= len(nums) <= 10^5, 1 <= k <= len(nums).

Brute force

Compute max(nums[i:i + k]) for each window: O(n x k), which is 10^10 when n and k are both large.

A heap of (value, index) with lazy deletion of out-of-window entries gives O(n log n).

Optimal approach

Deque dq of indices, values decreasing. For each index i:

  1. While dq is not empty and nums[dq[-1]] <= nums[i], pop from the back.
  2. Append i.
  3. If dq[0] <= i - k, pop from the front (it left the window).
  4. If i >= k - 1, the answer for this window is nums[dq[0]].

Why it works

If j < i and nums[j] <= nums[i], then j will leave the window before i and is never larger, so it can never be the maximum again; removing it is safe. That keeps values decreasing, so the front is the largest value among the indices still in the window. Out-of-window indices can only be at the front, because indices are added in increasing order.

Complexity

O(n) time: each index enters and leaves the deque at most once. O(k) space for the deque.

Code

python
from collections import deque


def max_sliding_window(nums, k):
    """Maximum of every window of size k using a monotonic deque. O(n)."""
    if k <= 0:
        raise ValueError("k must be positive")
    dq = deque()                     # indices; their values strictly decrease
    result = []
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()                 # smaller values can never be a future maximum
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()             # front index has left the window
        if i >= k - 1:
            result.append(nums[dq[0]])
    return result


def brute(nums, k):
    return [max(nums[i:i + k]) for i in range(len(nums) - k + 1)]


if __name__ == "__main__":
    for f in (max_sliding_window, brute):
        assert f([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
        assert f([1], 1) == [1]
        assert f([9, 8, 7, 6], 2) == [9, 8, 7]
        assert f([4, 4, 4], 2) == [4, 4]
        assert f([1, 2], 3) == []
    print("all tests passed")

Save as a26_sliding_max.py and run python3 a26_sliding_max.py. It prints all tests passed (Python 3.13.5).

Edge cases

k == 1 (output equals input). k == len(nums) (one value). Equal values (popping with <= keeps only the latest index, which stays in the window longest). Decreasing input (deque grows to k). k larger than the list returns an empty list in this implementation; k <= 0 raises.

Pattern

Monotonic deque (monotonic queue). It also solves "shortest subarray with sum at least k" (with prefix sums), jump-game DP optimisations, and maximum of fixed windows in streaming metrics.

python
from collections import deque


def max_sliding_window(nums, k):
    """Maximum of every window of size k using a monotonic deque. O(n)."""
    if k <= 0:
        raise ValueError("k must be positive")
    dq = deque()                     # indices; their values strictly decrease
    result = []
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()                 # smaller values can never be a future maximum
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()             # front index has left the window
        if i >= k - 1:
            result.append(nums[dq[0]])
    return result


def brute(nums, k):
    return [max(nums[i:i + k]) for i in range(len(nums) - k + 1)]


if __name__ == "__main__":
    for f in (max_sliding_window, brute):
        assert f([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
        assert f([1], 1) == [1]
        assert f([9, 8, 7, 6], 2) == [9, 8, 7]
        assert f([4, 4, 4], 2) == [4, 4]
        assert f([1, 2], 3) == []
    print("all tests passed")

Monotonic deque of indices; a brute force is checked on the same tests and in randomised cross-checks.

Complexity

Time: O(n). Space: O(k). A heap with lazy deletion would be O(n log n).

By level

Fresher: Explains the brute force and the idea of discarding smaller earlier values, then traces the deque on the example. Should explain why indices are stored rather than values.

Mid: Implements the deque correctly with index-based expiry and proves O(n). Handles equal values with a clear rule.

Senior: Applies monotonic queues to DP optimisation and prefix-sum problems, compares with heaps and sparse tables, and discusses streaming use. Explains where this structure speeds up dynamic programming.

Key points

  • Deque stores indices with decreasing values
  • Pop smaller or equal values from the back before pushing
  • Pop the front when it leaves the window
  • The front is the window maximum
  • Each index is pushed and popped once: O(n)

Common mistakes

  • Storing values instead of indices and losing track of the window
  • Forgetting to remove out-of-window indices
  • Claiming O(n k) is acceptable for large inputs
  • Popping only strictly smaller values and keeping stale duplicates without reason

Follow-ups

  • How would you get the window minimum?
  • How do you solve shortest subarray with sum at least k using a deque?
  • How would you compute window maxima on a stream with variable window size?

Tips

  • Explain why a smaller earlier value is useless
  • Store indices, not values
  • Give the amortised O(n) argument

Evaluation rubric

  • Correct deque algorithm
  • Correct amortised analysis
  • Handles window boundaries
  • Mentions heap alternative