← Whiteboard questions

Sliding Window Maximum

Find the largest value in every window of size k

DSA, Hard, Sliding Window

Which structure or algorithm, and what does it cost.

You get a list nums and a whole number k. Look at every block of k consecutive numbers, starting with the first k and shifting one place right each time, until the block ends at the last number. Return a list with the largest number of each block, in order.

Examples

Input nums = [4, 2, 12, 3, 8, 1, 7], k = 3
Output [12, 12, 12, 8, 8]
Why there are 5 windows. The first three all hold the 12, and the last two hold the 8.
Input nums = [9, 7, 5, 3, 1], k = 2
Output [9, 7, 5, 3]
Why the numbers only fall, so the maximum is always the left number of the window, and it leaves at the next step.
Input nums = [6, 1, 5], k = 3
Output [6]
Why the window is as long as the list, so there is only one window.

Constraints

Your answer must contain

Target Aim for O(n) time and O(k) memory.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Two neighbouring windows share all but one number. What could you keep from the last window, so you do not scan the shared part again?

Hint 2 the approach

If a new number is bigger than an older number in the window, the older one is useless: it leaves sooner and is smaller. You can discard it.

Hint 3 the key step

Keep positions in a double-ended queue, values falling from front to back. Pop smaller values from the back for a new number. Pop the front when it leaves.

Walkthrough

Full walkthrough brute force to best

Brute force

For each window, scan its k numbers and take the largest. There are n - k + 1 windows, so the cost is O(n * k) time and O(1) extra memory. With n = 100,000 and k = 50,000 that is about 2.5 billion steps, too slow.

Better method

Keep a max-heap of pairs (value, position). For each new number, push it. Before reading the maximum, pop the top while its position is outside the window. Then the top is the window maximum. This is O(n log n) time and O(n) memory, because old entries stay in the heap until they reach the top. It is correct, but slower than the best method.

Best method

Keep a double-ended queue of positions whose values fall from front to back. Walk the list. For a new number x, pop positions from the back while their value is not larger than x. Those numbers are older and not bigger, so they can never be a maximum again. Then push the position of x at the back. If the front position has left the window, pop it from the front. Once the first window is full, the value at the front is the maximum of the current window. The queue is sorted by value, so its front is the biggest value still in the window. Each position is pushed once and popped at most once, so the total work is linear.

Hand trace

Run on [4, 2, 12, 3, 8, 1, 7] with k = 3. Position 0 (4): queue [0]. Position 1 (2): 4 is bigger, so queue [0, 1]. Position 2 (12): pop 2, pop 4, queue [2]; the first window is full, record 12. Position 3 (3): queue [2, 3], record 12. Position 4 (8): pop 3, queue [2, 4], record 12. Position 5 (1): queue [2, 4, 5]. The front, position 2, is out of the window, so pop it and the queue is [4, 5]. Record 8. Position 6 (7): pop 1, queue [4, 6], record 8. The result is [12, 12, 12, 8, 8].

Code

from collections import deque
def window_maximums(nums, k):
    dq = deque()  # positions, values fall from front to back
    out = []
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out

Time and memory

O(n) time, because each position is pushed once and popped at most once. O(k) memory, because the queue never holds more than the k positions of one window.

Common mistakes

  • Storing values and popping equal ones from the back. With values, the front is dropped when it equals the number that leaves, and that is only safe when every equal copy stays in the queue. Positions avoid the question.
  • Forgetting to pop the front when it leaves the window. The answer then shows a number that is no longer in the window.
  • Recording a maximum before the first window is full. Record only when the position is at least k - 1.

Related problems

More Sliding Window problems
Sliding Window Maximum: walkthrough and Python solution