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.
dq (stores indices) and an empty result list.right, value val: while dq isn't empty and the value at its back index is smaller than val, pop from the back.right to dq.dq has fallen out of the window, pop it from the front.right >= k - 1), append the value at the front index to result.result.Time: O(n) — every index is pushed and popped from the deque at most once — Space: O(k)
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 resultHow the solution above works, piece by piece.
right, pop every smaller value off the back. They can never be a maximum again: val is bigger and stays in the window longer.if dq[0] <= right - k: dq.popleft(): the front index has slid out of the window, so drop it.right >= k − 1), append nums[dq[0]].Running it on nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3: