Idea
- Using monotonic queue to have the biggest element of the sliding window at the start of the queue
- We are using deque because it allows us to remove elements from rear (when the new element is bigger than the smallest element in the window)
- We have the first
while
to make sure the big number which is out of the window is removed
- We have the second
while
to make sure we remove all the elements smaller than the new element in the queue before adding the new element
- We only start adding the index to the res array when the window covers the minimum size
Space & time complexity analysis
- Space - O(n), the res & deque take n heap spaces in the worst case
- Time - O(n), we need to process each element once, and each element will be offered once & pop out at most once
Codes
- 1st attempt (java)
- 2nd attempt (java) ❤️❤️❤️