← All Exercises

Sliding Window Maximum with Monotonic Deque

basicjavascript~15min

Background

Sliding window maxima appear in streaming metrics, moving forecasts, and the first stage of several vision filters. The monotonic deque keeps each element relevant exactly once.

Problem

Given an array of integers and a window size k, output the maximum of each contiguous window of length k. Solve it in O(n) time using a deque of indexes whose values decrease from front to back.

Input

A JSON object {"nums": number[], "k": number} with 1 <= k <= nums.length.

Output

A JSON object {"maxima": number[]} of length nums.length - k + 1.

Sample tests

Sample 1

Input: {"nums":[1,3,-1,-3,5,3,6,7],"k":3}
Expected: {"maxima":[3,3,5,5,6,7]}

Sample 2

Input: {"nums":[4,4,4],"k":1}
Expected: {"maxima":[4,4,4]}

Sample 3

Input: {"nums":[9,1,1,9],"k":4}
Expected: {"maxima":[9]}

Your solution

Learning objective

Master the monotonic deque pattern for window extrema in linear time.