22. Sliding Window Maximum
hardAsked at Byju'sReturn the max of every contiguous window of size k as it slides across the array.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
You are given an array of integers nums, and there is a sliding window of size k which is moving from the very left to the very right of the array. You can only see the k numbers in the window. Each time the sliding window moves right by one position, return the max sliding window.
Constraints
1 <= nums.length <= 10^51 <= k <= nums.length-10^4 <= nums[i] <= 10^4
Examples
Example 1
nums = [1,3,-1,-3,5,3,6,7], k = 3[3,3,5,5,6,7]Example 2
nums = [1], k = 1[1]Approaches
1. Recompute max per window
Slide and call Math.max on each window slice.
- Time
- O(n*k)
- Space
- O(n)
const res=[];
for(let i=0;i<=nums.length-k;i++) res.push(Math.max(...nums.slice(i,i+k)));
return res;Tradeoff:
2. Monotonic deque of indices
Maintain a deque of indices whose values are strictly decreasing. The front is always the current window's max; pop expired indices off the front and smaller values off the back.
- Time
- O(n)
- Space
- O(k)
function maxSlidingWindow(nums, k) {
const dq = [], res = [];
for (let i = 0; i < nums.length; i++) {
if (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:
Byju's-specific tips
Byju's adaptive-learning telemetry aggregates rolling-window engagement signals, so the deque pattern maps directly onto their streaming analytics work.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Sliding Window Maximum and other Byju's interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →