SDE & MLE Prep

239. Sliding Window Maximum

Problem

A window of size k slides over nums one step at a time from the left. Return the maximum of each window position.

Example: nums = [1,3,-1,-3,5,3,6,7], k = 3 → [3,3,5,5,6,7]

Constraints: n ≤ 10⁵.

Keep a deque of indices with decreasing values. New element pops smaller ones from the back (they can never be a max again). Front is the max; drop it when it leaves the window.

nums 1 3 -1 -3 5 3 6 7, k=3
r=2  deque [3,-1]       max 3
r=3  deque [3,-1,-3]    max 3
r=4  5 pops all -> [5]  max 5

Complexity: O(n) time (each index pushed/popped once), O(k) space.

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        dq, res = deque(), []
        for i, x in enumerate(nums):
            while dq and nums[dq[-1]] <= x:
                dq.pop()
            dq.append(i)
            if dq[0] <= i - k:
                dq.popleft()
            if i >= k - 1:
                res.append(nums[dq[0]])
        return res