Complete the code to initialize the deque as an empty array.
const deque = [1];We use an empty array [] to represent the deque in JavaScript.
Complete the code to remove elements from the back of the deque while the current element is greater.
while (deque.length > 0 && nums[i] > nums[deque[[1]]]) { deque.pop(); }
We compare with the last element's index in the deque, which is at deque.length - 1.
Fix the error in removing elements from the front of the deque when they are out of the current window.
if (deque[0] <= i - [1]) { deque.shift(); }
i or nums.length which are not window sizes.We remove indices from the front if they are outside the window of size k.
Fill both blanks to add the current index to the deque and record the maximum for the window.
deque.push([1]); if (i >= [2] - 1) { result.push(nums[deque[0]]); }
We add the current index i to the deque. We start recording results when i reaches k - 1.
Fill all three blanks to complete the sliding window maximum function using deque.
function maxSlidingWindow(nums, [1]) { const deque = []; const result = []; for (let i = 0; i < nums.length; i++) { while (deque.length > 0 && nums[i] > nums[deque[[2]]]) { deque.pop(); } deque.push(i); if (deque[0] <= i - [3]) { deque.shift(); } if (i >= k - 1) { result.push(nums[deque[0]]); } } return result; }
The function parameter is k. We compare with the last element index deque.length - 1. We remove elements out of the window using k.
