Skip to main content

25. Sliding Window Maximum

hardAsked at Revolut

Return the max of every length-k window via a monotonic deque, a Revolut hard-screen that mirrors computing rolling peak FX volatility over a sliding minute window.

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

Problem

Given an integer array nums and an integer k, return the maximum of each sliding window of size k as the window moves from left to right. Output length is n - k + 1.

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. Recompute each window

For each window of size k, take Math.max.

Time
O(n*k)
Space
O(1)
for (let i=0;i<=n-k;i++) res.push(Math.max(...nums.slice(i,i+k)));

Tradeoff:

2. Monotonic deque of indices

Keep a deque of indices in decreasing value order; pop expired (< i-k+1) from front and pop smaller from back. Front is the current window max.

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

Tradeoff:

Revolut-specific tips

Revolut graders care that you can articulate the deque invariant — they want to hear that any value smaller than a newer arrival is permanently dominated, exactly the same logic you use to evict stale FX-volatility samples.

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

Practice these live with InterviewChamp.AI →