#239
Sliding Window Maximum
HardArrayQueueSliding WindowHeap (Priority Queue)Monotonic QueueSliding WindowDequeMonotonic Queue
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a deque (double-ended queue) to keep track of the indices of the maximum values in the current window. This allows us to efficiently add and remove elements as the window slides.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a deque to store indices of the elements in nums.
- 2Step 2: Loop through each element in nums, maintaining the deque to ensure it only contains indices of elements in the current window and in decreasing order of their values.
- 3Step 3: For each index, if the index is out of the current window, remove it from the front of the deque.
- 4Step 4: Append the maximum (nums[deque[0]]) to the result list once the first window is filled.
solution.py17 lines
1# Full working Python code
2from collections import deque
3
4def maxSlidingWindow(nums, k):
5 if not nums:
6 return []
7 max_values = []
8 dq = deque()
9 for i in range(len(nums)):
10 if dq and dq[0] < i - k + 1:
11 dq.popleft()
12 while dq and nums[dq[-1]] < nums[i]:
13 dq.pop()
14 dq.append(i)
15 if i >= k - 1:
16 max_values.append(nums[dq[0]])
17 return max_valuesℹ
Complexity note: The time complexity is O(n) because each element is added and removed from the deque at most once. The space complexity is O(n) due to the storage of indices in the deque.
- 1Using a deque allows us to efficiently manage the maximums in the current window.
- 2The sliding window technique is useful for problems involving contiguous subarrays.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.