Python coding

Maximum of every window

Given a list of integers nums and a window size k, slide a window of k consecutive elements from left to right, one position at a time, and return the maximum of each window, in order. The result has len(nums) - k + 1 values.

Constraints: 1 <= k <= len(nums). Aim for O(n): taking max of every window is O(n·k).

Besides the tests, one large input (18,000 numbers, window 9,000) with a ~400 ms limit (scaled to your device's speed): brute force won't pass.

  • window_maxima([4,2,7,1,3,6,5], 3) → [7,7,7,6,6]
  • window_maxima([9,8,7,6,5], 2) → [9,8,7,6]
  • window_maxima([1,5,5,1,1,1], 3) → [5,5,5,1]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Recomputing max for each window is O(n·k). Which elements of the current window can still become a maximum later on?

Hint 2

Keep a deque of indexes with decreasing values: before adding index i, pop from the back every index whose value is <= nums[i]. The front is the window's maximum.

Hint 3

Drop the front when its index is <= i - k (it left the window), and start recording only once the first full window exists, at i >= k - 1.

Solution and why it works
pythonO(n) · O(k) besides the output
from collections import deque

def window_maxima(nums: list[int], k: int) -> list[int]:
    dq = deque()                      # indexes; their values decrease from front to back
    out = []
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()                  # older and not larger: never a maximum again
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()              # the front slid out of the window
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out

An element that is older and not larger than a newer one can never be a window's maximum again, so pop it from the back before adding the new index. The deque then holds decreasing values, and its front is the maximum once you drop a front whose index has left the window. Each index enters and leaves once: O(n). Store indexes, not values, or you cannot tell when the front expires; pop with while, not if, or the order breaks.