Skip to main content

21. Sliding Window Maximum

hardAsked at Rappi

Return the max in each window of size k as it slides across the array — Rappi frames this as reporting the peak courier supply in a rolling time-window during dispatch matching.

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

Problem

Given an array nums and a window size k, return an array of the maximum of each contiguous window of length k.

Constraints

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

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. Recompute max per window

For each window, scan all k elements to find the max.

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

Tradeoff:

2. Monotonic deque

Maintain a deque of indices whose values strictly decrease; pop the back when a larger value arrives, pop the front when it falls out of the window. Front is always the max.

Time
O(n)
Space
O(k)
function maxSlidingWindow(nums, k) {
  const dq = [], out = [];
  for (let i = 0; i < nums.length; i++) {
    while (dq.length && dq[0] <= i - k) dq.shift();
    while (dq.length && nums[dq.at(-1)] < nums[i]) dq.pop();
    dq.push(i);
    if (i >= k - 1) out.push(nums[dq[0]]);
  }
  return out;
}

Tradeoff:

Rappi-specific tips

Rappi explicitly tests the monotonic-deque pattern — their rolling-supply metric uses the exact same data structure to avoid O(nk) per dispatch tick.

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 Rappi interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →