Sliding Window Maximum Problem
Description
LeetCode Problem 239.
You are given an array of integersnums, there is a sliding window of size k which is moving from the very left of the array to the very right. 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.
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position Max
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
Example 2:
Input: nums = [1], k = 1
Output: [1]
Example 3:
Input: nums = [1,-1], k = 1
Output: [1,-1]
Example 4:
Input: nums = [9,11], k = 2
Output: [11]
Example 5:
Input: nums = [4,-2], k = 2
Output: [4]
Constraints:
- 1 <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
- 1 <= k <= nums.length
Solution
Approach: Monotonic Deque
Scanning each window takes O(n·k) time. Instead, keep a deque of indices whose values are strictly decreasing from front to back. The front is then always the maximum of the current window.
For each index i:
- While the value at the back of the deque is
<= nums[i], pop it. Such an element is older and not larger thannums[i], so it leaves the window first and is never needed as the maximum whilenums[i]is around. - Push
ito the back. - If the front index is
<= i - k, it has slid out of the window[i - k + 1, i]; pop it from the front. Only the front can be out of range, because the deque is in index order and the window moves one step at a time. - Once
i >= k - 1, the window is full: appendnums[front]to the answer.
Storing indices rather than values is what makes step 3 possible: we need to know when an element leaves the window.
Complexity: O(n) time, where n is the length of nums, since each index is pushed and popped at most once. O(k) extra space for the deque, which never holds more than k + 1 indices (the JavaScript and Go versions drop from the front by moving a head index, so their array can grow to n).
import collections
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
window = collections.deque() # indices; their values decrease from front to back
answer = []
for i, x in enumerate(nums):
# Smaller values to the left of x can never be a window maximum again.
while window and nums[window[-1]] <= x:
window.pop()
window.append(i)
# Drop the front index once it has slid out of the window [i - k + 1, i].
if window[0] <= i - k:
window.popleft()
if i >= k - 1:
answer.append(nums[window[0]])
return answer