Sliding Window Maximum
To solve this coding challenge, we need to find the maximum value within a sliding window of size
that moves from the left to the right end of the array. We are provided with an array of integers
and the window size
. Each time the window moves one position to the right, we need to capture the maximum value in the window and return a list of these maximum values.
k
nums
k
# Explanation
Here, weβll break down the solution and explain how to solve this challenge using a deque:-
A deque (double-ended queue) will be used to store indices of the elements in
nums
- As we iterate over the array, we'll keep the deque in such a state that:
-
The elements' indices are in descending order based on their corresponding values in
nums
- The left-most element in the deque is the index of the maximum element for the current window.
- For each element, we:
-
Remove elements from the deque that are out of the current windowβs range (i.e., their indices are less than the current index minus
k
- Maintain the descending order in the deque by removing elements from the back of the deque as long as the current element is greater than the elements corresponding to those indices in the deque.
- Add the current element's index to the deque.
-
If we have processed at least
k
- Initialize the deque and the result list.
- Iterate over each index and element in the array.
- Adjust the deque by removing indices that are out of the current window.
- Maintain the deque's descending order by removing smaller elements from the back.
- Append the current index to the deque.
-
Once the first
k
Step-by-Step Explanation/Detailed Steps in Pseudocode:
Pseudocode with Comments
# Initialize deque for storing indices and a list for result
result = []
window = deque()
# Iterate through the given nums list
for i = 0 to length(nums) - 1:
# Remove elements from the back of the deque if they are smaller than current element
while window is not empty and nums[window[-1]] < nums[i]:
window.pop() # remove from back
# Add current element index to the back of deque
window.append(i)
# Remove the front element if it is out of the current window
if window[0] == i - k:
window.popleft() # remove from front
# Append result with the max value of the current window
# window[0] is the index of the maximum element for the current window
if i >= k - 1:
result.append(nums[window[0]])
return result
In the above pseudocode:
-
window.pop()
-
window.popleft()
-
nums[window[0]]
nums