Overview
A Monotonic Queue is commonly implemented using a deque. It removes elements that can no longer affect future minimum or maximum results, keeping only useful candidates in sorted order.
How it works
Process incoming elements one at a time.; Remove elements from the back while they are dominated by the new element.; Insert the new element at the back.; Remove expired elements from the front when they leave the current window.; The front element represents the current minimum or maximum.
Key concepts
Double-ended queue; Monotonic ordering; Candidate elements; Window expiration; Minimum and maximum queries; Amortized complexity
Types
name: Increasing Monotonic Queue; description: Stores candidate elements in increasing order and is useful for minimum queries.; name: Decreasing Monotonic Queue; description: Stores candidate elements in decreasing order and is useful for maximum queries.
Time complexity
operation: Processing all elements; complexity: O(n) amortized; operation: Insertion; complexity: O(1) amortized; operation: Removal; complexity: O(1) amortized
Space complexity
O(k) for a sliding window of size k.
Example
array: 4; 2; windowSize: 3; problem: Find the maximum in each sliding window of size 3.; results: window: 4; 2; maximum: 12; window: 2; 12; maximum: 12