CodeArchon

hardSliding WindowAmazonGoogleLinkedIn

Window Peak Scanner

A moving spotlight of width k scans a row of sensor readings. For every spotlight position, report the brightest reading inside it.

Given an integer array `nums` and window size `k`, return the maximum value in every window of length k as it slides left-to-right.

Choose approach

1
0
3
1
-1
2
-3
3
5
4
3
5
6
6
7
7
Mapdeque (idx→val)
empty
1/23
Narrationstep 1 of 23

Monotonic deque of indices whose values are strictly decreasing. The front is always the maximum of the current window.

1from collections import deque
2
3def window_peak_scanner(nums: list[int], k: int) -> list[int]:
4 dq = deque() # indices, values decreasing
5 out: list[int] = []
6 for i, v in enumerate(nums):
7 while dq and dq[0] <= i - k:
8 dq.popleft()
9 while dq and nums[dq[-1]] < v:
10 dq.pop()
11 dq.append(i)
12 if i >= k - 1:
13 out.append(nums[dq[0]])
14 return out
Variables
k=3
i=0

How to think about it

  1. A value smaller than a later value can never be a future max — pop it from the back.
  2. Indices that fall out of the window must be popped from the front.
  3. Each index is pushed and popped at most once → amortized O(n).
  4. Emit result from index k − 1 onward (first full window).

Edge cases to catch in interview

  • k = 1 → every element is its own window max.
  • k = n → single answer = max of array.
  • Negative numbers — unchanged logic.

Examples

Example 1[3, 3, 5, 5, 6, 7]
{"nums":[1,3,-1,-3,5,3,6,7],"k":3,"values":[1,3,-1,-3,5,3,6,7]}
Example 2[1]
{"nums":[1],"k":1,"values":[1]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed