Skip to main content

23. Sliding Window Maximum

hardAsked at Redis

Find the max of every window of size k as it slides across an array; Redis uses it to probe deque/monotonic intuition that mirrors LPUSH/RPOP patterns on Redis Lists.

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

Problem

Given an integer array nums and a window size k, return an array of the maximum value within every contiguous window. Must run in O(n).

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

Slide the window and call Math.max on each.

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

Tradeoff:

2. Monotonic deque

Maintain a deque of indices whose values are strictly decreasing. Pop from the back while the new element is bigger; pop from the front when it falls out of the window. The front is always the window max. This mirrors how Redis Lists drive backpressure via LPUSH + LPOP.

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

Tradeoff:

Redis-specific tips

Redis interviewers like the monotonic-deque framing because that's how Redis Streams XREAD windowing throttles back-pressure; cite quicklist's deque-like ends as a side reference.

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

Practice these live with InterviewChamp.AI →