239. Sliding Window Maximum
Asked at 48Amazon66Microsoft56Google55Meta55Bloomberg53Apple35Nutanix96Verily83Expedia79DE Shaw71Faire71Juspay69Nvidia64Walmart Labs53Infosys45tcs42Citadel100Cohesity100LINE100Zenefits100blinkit100Zepto87Aurora77Oracle77ServiceNow73Booking.com70Coupang68Zeta64Wayfair62MongoDB61Agoda57Sprinklr54American Express53PhonePe53IBM50Palo Alto Networks50ByteDance50TikTok50Uber47Goldman Sachs47Adobe44Zoho42DoorDash41Salesforce41Visa39Cisco37Roblox37Yandex28
Problem
A window of size k slides over nums one step at a time from the left. Return the maximum of each window position.
Example: nums = [1,3,-1,-3,5,3,6,7], k = 3 → [3,3,5,5,6,7]
Constraints: n ≤ 10⁵.
Keep a deque of indices with decreasing values. New element pops smaller ones from the back (they can never be a max again). Front is the max; drop it when it leaves the window.
nums 1 3 -1 -3 5 3 6 7, k=3
r=2 deque [3,-1] max 3
r=3 deque [3,-1,-3] max 3
r=4 5 pops all -> [5] max 5
Complexity: O(n) time (each index pushed/popped once), O(k) space.
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
dq, res = deque(), []
for i, x in enumerate(nums):
while dq and nums[dq[-1]] <= x:
dq.pop()
dq.append(i)
if dq[0] <= i - k:
dq.popleft()
if i >= k - 1:
res.append(nums[dq[0]])
return res
assert Solution().maxSlidingWindow([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
assert Solution().maxSlidingWindow([1], 1) == [1]
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
Deque<Integer> dq = new ArrayDeque<>();
int[] res = new int[nums.length - k + 1];
for (int i = 0; i < nums.length; i++) {
while (!dq.isEmpty() && nums[dq.peekLast()] <= nums[i]) dq.pollLast();
dq.addLast(i);
if (dq.peekFirst() <= i - k) dq.pollFirst();
if (i >= k - 1) res[i - k + 1] = nums[dq.peekFirst()];
}
return res;
}
}
func maxSlidingWindow(nums []int, k int) []int {
dq, res := []int{}, []int{} // indices, values decreasing
for i, x := range nums {
for len(dq) > 0 && nums[dq[len(dq)-1]] <= x {
dq = dq[:len(dq)-1]
}
dq = append(dq, i)
if dq[0] <= i-k {
dq = dq[1:]
}
if i >= k-1 {
res = append(res, nums[dq[0]])
}
}
return res
}