Skip to main content

25. Sliding Window Maximum

hardAsked at DigitalOcean

Return the max of every k-length sliding window in O(n) using a monotonic deque — a high-value hard problem that tests real-time metrics aggregation thinking.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an integer array nums and an integer k, return an array of the maximum value in each sliding window of size k as the window moves from left to right.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length

Examples

Example 1

Input
nums = [1,3,-1,-3,5,3,6,7], k = 3
Output
[3,3,5,5,6,7]

Example 2

Input
nums = [1], k = 1
Output
[1]

Approaches

1. Brute force (nested loops)

For each window position, scan k elements to find the max — O(n*k) time, too slow for large inputs.

Time
O(n*k)
Space
O(1)
function maxSlidingWindow(nums, k) {
  const result = [];
  for (let i=0;i<=nums.length-k;i++) {
    let max = -Infinity;
    for (let j=i;j<i+k;j++) max = Math.max(max, nums[j]);
    result.push(max);
  }
  return result;
}

Tradeoff:

2. Monotonic deque (decreasing)

Maintain a deque of indices in decreasing order of nums value. Remove indices outside the window from the front; pop smaller elements from the back before adding the current index. Front of deque is always the window max.

Time
O(n)
Space
O(k)
function maxSlidingWindow(nums, k) {
  const deq = []; // stores indices, decreasing by nums value
  const result = [];
  for (let i=0;i<nums.length;i++) {
    // remove indices outside window
    if (deq.length && deq[0] < i-k+1) deq.shift();
    // maintain decreasing invariant
    while (deq.length && nums[deq[deq.length-1]] < nums[i]) deq.pop();
    deq.push(i);
    if (i >= k-1) result.push(nums[deq[0]]);
  }
  return result;
}

Tradeoff:

DigitalOcean-specific tips

DigitalOcean's monitoring stack aggregates per-second metrics in rolling windows — framing the deque as a time-series max-tracker resonates strongly with interviewers.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Sliding Window Maximum and other DigitalOcean interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →