Problem
Given an integer array and a window length k, return an array of the maximum value in every contiguous window of length k, in order from left to right.
Original: LeetCode 239: Sliding Window Maximum.
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]`Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^41 <= k <= nums.length
Hints
Hint 1
The first window covers indices 0 to k-1, then the window moves one step at a time. You need the maximum of each window, not the index of that maximum.
Hint 2
A sliding window whose best value must be retrieved in better than linear time per move is a monotonic deque problem: store candidates in decreasing order.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Scan each window and take the max. That is O(nk) time.
Optimal. Store indices in a deque, with values in decreasing order. The front is the window maximum. Drop the front when it leaves the window, and drop from the back while the new value is greater than or equal to the value at the back, then push the new index.
Alternative. A sparse table or a segment tree also answers range-maximum queries in logarithmic time, but they are heavier than a deque for a sliding window.
Complexity
- Time
- O(n)
O(n) time, because each index is pushed and popped at most once. O(k) extra space for the deque.
- Space
- O(k)
Code
from collections import deque
def max_sliding_window(nums: list[int], k: int) -> list[int]:
dq = deque()
ans = []
for i, x in enumerate(nums):
if dq and dq[0] <= i - k:
dq.popleft()
while dq and nums[dq[-1]] <= x:
dq.pop()
dq.append(i)
if i >= k - 1:
ans.append(nums[dq[0]])
return ans
if __name__ == "__main__":
assert max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
assert max_sliding_window([1], 1) == [1]
print("ok")import java.util.ArrayDeque;
import java.util.Arrays;
public class SlidingWindowMaximum {
static int[] maxSlidingWindow(int[] nums, int k) {
var dq = new ArrayDeque<Integer>();
int n = nums.length;
int[] ans = new int[n - k + 1];
for (int i = 0; i < n; i++) {
if (!dq.isEmpty() && dq.peekFirst() <= i - k) dq.pollFirst();
while (!dq.isEmpty() && nums[dq.peekLast()] <= nums[i]) dq.pollLast();
dq.addLast(i);
if (i >= k - 1) ans[i - k + 1] = nums[dq.peekFirst()];
}
return ans;
}
public static void main(String[] args) {
int[] a = maxSlidingWindow(new int[] {1, 3, -1, -3, 5, 3, 6, 7}, 3);
if (!Arrays.equals(a, new int[] {3, 3, 5, 5, 6, 7})) throw new AssertionError(Arrays.toString(a));
int[] b = maxSlidingWindow(new int[] {1}, 1);
if (!Arrays.equals(b, new int[] {1})) throw new AssertionError(Arrays.toString(b));
System.out.println("ok");
}
}Edge cases
- Official samples: [1,3,-1,-3,5,3,6,7] with k = 3 returns [3,3,5,5,6,7], and [1] with k = 1 returns [1].
- Equal values: drop the older equal index from the back, because the newer one stays in the window longer.
Follow-ups
- Sliding window minimum is the same idea with an increasing deque.
- If k equals 1, the answer is a copy of the array.
Interview script
"A heap of the window would cost a log factor and need lazy deletions. A decreasing deque of indices keeps the maximum at the front, and each index enters and leaves the deque once, so the whole scan is linear."
Source: LeetCode 239: Sliding Window Maximum Source: Java SE 17 API: ArrayDeque
Sources
- LeetCode 643: Maximum Average Subarray I
- LeetCode 438: Find All Anagrams in a String
- Java SE 17 API: Arrays.equals)
- LeetCode 567: Permutation in String
- HackerRank: Fraudulent Activity Notifications
- LeetCode 3: Longest Substring Without Repeating Characters
- Java SE 17 API: HashMap
- LeetCode Discuss: Microsoft SDE-2 recent questions 2025 (candidate reports, secondary)
- LeetCode 904: Fruit Into Baskets
- Java SE 17 API: Map.merge)
- LeetCode 424: Longest Repeating Character Replacement
- LeetCode 1004: Max Consecutive Ones III
- LeetCode 209: Minimum Size Subarray Sum
- LeetCode 76: Minimum Window Substring
- Java SE 17 API: String.substring)
- LeetCode 992: Subarrays with K Different Integers
- LeetCode 239: Sliding Window Maximum
- Java SE 17 API: ArrayDeque
Sources (2)
- LeetCode 239: Sliding Window Maximumleetcode.com
- Java SE 17 API: ArrayDequedocs.oracle.com