CodingNodes / Sliding Window / Sliding Window Maximum System design Space play · ←→ step · R restart

Problem

You are given an integer array nums and a window size k. The window starts over the first k numbers and slides one step to the right each time, until it reaches the end of the array.

Return a list with the largest number inside the window at every position.

Constraints

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

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(k)

Time: Each index is pushed onto the deque once and popped at most once (from the back or the front), so the total work is at most 2n deque operations.

Space: The deque holds indices from the current window only, so at most k entries (the output list is not counted).

Keep a deque of indices whose values decrease from front to back. A new number first pops every smaller or equal number off the back, since those can never win again. Then pop the front if it has slid out of the window. The front of the deque is always the maximum of the window.