Module 4Stack, Queue & DequeLesson 17 of 2324 min
Deque: Both Ends & Sliding Window
push/pop front and back; monotonic deque for sliding window max.
Full deque ops
rust
q.push_front(x);
q.push_back(x);
q.pop_front();
q.pop_back();
q.front(); q.back();Sliding window maximum
Maintain deque of indices with decreasing values:
- Pop back while
nums[back] <= nums[i]
- Push i
- Pop front if out of window
- Front is max for window ending at i
Time O(n). Classic hard interview favorite.
Challenge
Sliding window minimum by flipping the comparison.
Tips
- Store indices not values
- Monotonic deque
- Amortized O(n)
Try it live
Deque: Both Ends & Sliding WindowRust 2021
Loading editor…
Output
Press Run to compile and execute.