← DSA
HARD

Sliding Window Maximum

PracticeNeetCode ↗LeetCode ↗

Given an array nums and a window size k, return an array of the maximum value in each window of size k as it slides from the start of nums to the end.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Initialize an empty deque dq (stores indices) and an empty result list.
  2. For each index right, value val: while dq isn't empty and the value at its back index is smaller than val, pop from the back.
  3. Append right to dq.
  4. If the index at the front of dq has fallen out of the window, pop it from the front.
  5. Once the window has filled (right >= k - 1), append the value at the front index to result.
  6. Return result.

Complexity

Time: O(n) — every index is pushed and popped from the deque at most once — Space: O(k)

Code

from collections import deque

def maxSlidingWindow(nums: list[int], k: int) -> list[int]:
    dq = deque()
    result = []

    for right, val in enumerate(nums):
        while dq and nums[dq[-1]] < val:
            dq.pop()
        dq.append(right)

        if dq[0] <= right - k:
            dq.popleft()

        if right >= k - 1:
            result.append(nums[dq[0]])

    return result

Code Explanation

How the solution above works, piece by piece.

  1. The deque holds indices whose values are decreasing from front to back, so the front is always the window's maximum.
  2. Before adding right, pop every smaller value off the back. They can never be a maximum again: val is bigger and stays in the window longer.
  3. if dq[0] <= right - k: dq.popleft(): the front index has slid out of the window, so drop it.
  4. Once the first full window exists (right >= k − 1), append nums[dq[0]].
  5. Each index is pushed and popped at most once: O(n) total, versus O(n·k) for scanning every window.

Visual Walkthrough

Running it on nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3:

trace1031-12-3354356677r=01window filling13-1-35367r=13window filling13-1-35367r=23-1max 313-1-35367r=33-1-3max 313-1-35367r=45max 513-1-35367r=553max 513-1-35367r=66max 613-1-35367r=77max 7
Blue is the window, amber its maximum. The deque (values shown on the right) stays decreasing, so its front is the answer for each window: 3, 3, 5, 5, 6, 7.
windowmaximum / deque front

Video Explanation

NeetCode — Sliding Window Maximum, LeetCode 239