Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Sliding Window Maximum

Sliding Windowhard

Implement `maxSlidingWindow(nums, k)` that returns an array of the maximum value within each contiguous window of size `k` as the window slides left to right. Aim for O(n).

Examples

Input: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Output: [3, 3, 5, 5, 6, 7]
Input: nums = [9, 8, 7], k = 2
Output: [9, 8]

Sample tests

Input: maxSlidingWindow([1,3,-1,-3,5,3,6,7], 3)
Output: [3,3,5,5,6,7]
Input: maxSlidingWindow([9,8,7], 2)
Output: [9,8]

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Storing values instead of indices makes it impossible to know when an entry leaves the window.
  • Only recording results once `i >= k - 1` — earlier the first window is incomplete.

Learning resources

  • Wikipedia: Array data structure
Approach & explanation (try first)

A monotonic deque keeps candidate maxima in decreasing order. Smaller trailing values are discarded because a later, larger value dominates them for the rest of their lifetime. Each index enters and leaves the deque once, so the whole pass is O(n).

Loading...
⌘/Ctrl + Enter

Run your code to see results.