Workspace

Problem workspace

3 day streakD

Sliding Window Maximum

HardSliding WindowMonotonic deque

The challenge

Return the maximum value in every consecutive window of exactly k elements.

Use 1 ≤ k ≤ n. Values may be negative. Indices are zero-based.

Example

[1, 3, −1, −3, 5, 3, 6, 7], k = 3 → [3, 3, 5, 5, 6, 7].

Use the walkthrough below to inspect the input and each state change.

See Window maximum, step by step

Expand, shrink, and inspect the window state.

8 elements · zero-based indicesk = 3
Sliding window over 8 elementsThe current window is empty. Both boundaries move forward. Watch what enters, what leaves, and when the answer changes.Empty window · L = 0, R = -11031-12-3354356677
Current windowRecorded answerOutside window
Left
0
Right
-1
Length
0
Step 01 / 16

Start with an empty window

Both boundaries move forward. Watch what enters, what leaves, and when the answer changes.

left = 0; right = −1

Answer so far

[]
View exact input

Input: [1,3,-1,-3,5,3,6,7] · k = 3

Current window is empty.

Put it into code

Keep candidate indices with decreasing values. A newer value that is at least as large dominates older smaller candidates and expires later.

Indices are zero-based. C++ uses C++17 or later.

from collections import deque


def window_maxima(nums, k):
    candidates = deque()  # Indices; values decrease front to back.
    answer = []
    for right, value in enumerate(nums):
        left = right - k + 1
        while candidates and candidates[0] < left:
            candidates.popleft()
        while candidates and nums[candidates[-1]] <= value:
            candidates.pop()
        candidates.append(right)
        if left >= 0:
            answer.append(nums[candidates[0]])
    return answer

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap