Skip to main content

23. Sliding Window Maximum

hardAsked at N26

Given an array and a window size k, return the maximum in each window as it slides left to right. N26 uses this for real-time peak-debit detection in their fraud-monitoring stream.

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

Problem

You are given an array of integers nums and an integer k representing the window size. Return an array containing the maximum value in each sliding window 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. Recompute max per window

For each window start i, scan k elements and take the max.

Time
O(n*k)
Space
O(1)
const ans = [];
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]);
  ans.push(m);
}
return ans;

Tradeoff:

2. Monotonic deque

Keep a deque of indices whose values are strictly decreasing. Pop the front when it leaves the window; pop the back while it is smaller than the incoming value. The front is always the window max in O(1) amortized.

Time
O(n)
Space
O(k)
function maxSlidingWindow(nums, k) {
  const dq = []; // indices, values decreasing
  const ans = [];
  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) ans.push(nums[dq[0]]);
  }
  return ans;
}

Tradeoff:

N26-specific tips

N26 likes when you call out that the monotonic deque is what their fraud stream uses to compute rolling 60-second peak-debit values without re-scanning the buffer per 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 N26 interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →