InterviewPrepKit

Home / Coding / Sliding Window

Sliding Window Maximum

hard Original β†—
Solving tips
  • Recognize the monotonic-deque pattern: a running sum/count fails for extrema, so keep a deque of indices whose values are strictly decreasing front-to-back.
  • Key insight: if a newer element is >= an older one still in the window, the older can never be a future max, so pop it from the back.
  • The front is always the current window's max; pop the front when its index slides out (dq[0] <= i-k), and emit once i >= k-1.
  • Target O(n) time and O(k) space (each index pushed/popped once); store indices not values so you can detect expiry. A max-heap with lazy deletion is an O(n log n) alternative.

Problem

You are given an integer array nums and a window size k. A window of size k starts at the left edge of the array and slides one position to the right at a time until it reaches the right edge. For each of the n - k + 1 window positions, report the maximum value inside the window. Return these maxima as a list, in order.

Examples

  • nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3 β†’ [3, 3, 5, 5, 6, 7] β€” e.g. the first window [1, 3, -1] has max 3; the third window [-1, -3, 5] has max 5.
  • nums = [1], k = 1 β†’ [1] β€” a single window containing the single element.
  • nums = [9, 8, 7, 6], k = 2 β†’ [9, 8, 7] β€” a strictly decreasing array: each window’s max is its left element.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= len(nums)
  • With n and k both up to 10^5, the O(nΒ·k) rescan-every-window approach is up to 10^10 operations β€” you need roughly O(n log n) or O(n).

Think about it first

Hint 1 When the window slides, it loses one element and gains one. Gaining is easy to handle; the trouble is when the element that *leaves* was the maximum. What cheap structure can hand you the next-best candidate?
Hint 2 Suppose the window contains an element `x`, and to its right (also in the window) sits a larger element `y`. Can `x` ever be the answer for this or any future window? If not, you can discard `x` forever the moment `y` arrives.
Hint 3 Keep a double-ended queue of indices whose values are strictly decreasing front-to-back. On each new element: pop smaller-or-equal values off the back, push the new index, pop the front if it has slid out of the window. The front is always the current window's maximum, and every index is pushed and popped at most once.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.