Sliding Window Maximum Using Deque in DSA Javascript - Time & Space Complexity
We want to know how fast we can find the maximum in every sliding window of an array.
How does the time needed grow as the array gets bigger?
Analyze the time complexity of the following code snippet.
function maxSlidingWindow(nums, k) {
const deque = [];
const result = [];
for (let i = 0; i < nums.length; i++) {
while (deque.length && nums[deque[deque.length - 1]] < nums[i]) {
deque.pop();
}
deque.push(i);
if (deque[0] === i - k) deque.shift();
if (i >= k - 1) result.push(nums[deque[0]]);
}
return result;
}
This code finds the maximum value in every window of size k as it slides over the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single loop over the array elements.
- How many times: Each element is added and removed from the deque at most once.
As the array size grows, each element is processed a limited number of times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (each element pushed and popped once) |
| 100 | About 200 |
| 1000 | About 2000 |
Pattern observation: The operations grow roughly in a straight line with input size.
Time Complexity: O(n)
This means the time to find all sliding window maximums grows directly with the size of the input array.
[X] Wrong: "Because of the nested while loop, the time complexity is O(n*k)."
[OK] Correct: Each element is pushed and popped at most once, so the inner loop does not run for every element repeatedly, keeping the total operations linear.
Understanding this efficient approach shows you can optimize from a simple but slow method to a smart, fast one using the right data structure.
"What if we used a simple array instead of a deque to store indices? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of deque in the algorithm
The deque stores indices of elements in the current window, maintaining them in decreasing order of their values to quickly find the maximum.Step 2: Why other options are incorrect
To store all elements of the array for quick access is incorrect because deque does not store all elements, only relevant indices. To sort the entire array before processing and D do not relate to the sliding window maximum logic.Final Answer:
To keep track of indices of elements in the current window in decreasing order of their values -> Option CQuick Check:
Deque stores indices in decreasing order for max [OK]
- Thinking deque stores actual values instead of indices
- Assuming deque sorts the entire array
- Confusing deque with a stack or queue without order
Solution
Step 1: Identify JavaScript data structure for deque
JavaScript does not have a built-in Deque class, so an empty array is used to simulate a deque.Step 2: Why other options are invalid
Options A, B, and D refer to classes not available in standard JavaScript.Final Answer:
const deque = []; -> Option DQuick Check:
Use array as deque in JS [OK]
- Trying to use non-existent Deque class
- Using Queue which lacks double-ended operations
- Confusing JavaScript with other languages' syntax
function maxSlidingWindow(nums, k) {
const deque = [];
const result = [];
for (let i = 0; i < nums.length; i++) {
while (deque.length && nums[deque[deque.length - 1]] <= nums[i]) {
deque.pop();
}
deque.push(i);
if (deque[0] <= i - k) {
deque.shift();
}
if (i >= k - 1) {
result.push(nums[deque[0]]);
}
}
return result;
}
console.log(maxSlidingWindow([1,3,-1,-3,5,3,6,7], 3));Solution
Step 1: Trace the sliding window maximum for each window
Windows of size 3 and their max values are: [1,3,-1] -> 3, [3,-1,-3] -> 3, [-1,-3,5] -> 5, [-3,5,3] -> 5, [5,3,6] -> 6, [3,6,7] -> 7.Step 2: Confirm the result array matches the expected output
The result array is [3, 3, 5, 5, 6, 7], matching [3, 3, 5, 5, 6, 7].Final Answer:
[3, 3, 5, 5, 6, 7] -> Option BQuick Check:
Sliding window max = [3,3,5,5,6,7] [OK]
- Not removing indices outside the window
- Pushing values instead of indices into deque
- Incorrectly updating the result array
function maxSlidingWindow(nums, k) {
const deque = [];
const result = [];
for (let i = 0; i < nums.length; i++) {
while (deque.length && nums[deque[0]] <= nums[i]) {
deque.shift();
}
deque.push(i);
if (deque[0] <= i - k) {
deque.shift();
}
if (i >= k - 1) {
result.push(nums[deque[0]]);
}
}
return result;
}Solution
Step 1: Analyze the while loop condition
The while loop incorrectly compares nums[deque[0]] (front) with nums[i], but it should compare with nums[deque[deque.length - 1]] (back) to maintain decreasing order.Step 2: Confirm other parts are correct
The deque stores indices correctly, the out-of-window removal condition exists, and the result is returned properly.Final Answer:
The condition in the while loop should compare with the last element, not the first -> Option AQuick Check:
Compare with deque's last element in while loop [OK]
- Comparing with front instead of back in deque
- Storing values instead of indices in deque
- Forgetting to remove indices outside the window
nums = [4, 2, 12, 3, 8, 7, 9] and window size k = 4, what will be the output of the Sliding Window Maximum algorithm using a deque?Solution
Step 1: Identify each window and its maximum
Windows of size 4 are: [4,2,12,3] max=12, [2,12,3,8] max=12, [12,3,8,7] max=12, [3,8,7,9] max=9.Step 2: Collect the maximums in order
The result array is [12, 12, 12, 9], matching [12, 12, 12, 9].Final Answer:
[12, 12, 12, 9] -> Option AQuick Check:
Max per window = [12,12,12,9] [OK]
- Not sliding window correctly by one index
- Forgetting to remove old indices from deque
- Mixing values and indices in deque
Ready to prove it?
Pass the test and this pattern moves unknown
