InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Sliding Window

Sliding Window Maximum

hard Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug