Data Structures and Algorithms • C# examples
Monotonic Stacks and Monotonic Queues
Solve next-greater, nearest-smaller, and fixed-window-extreme problems in linear time.
Concept
A monotonic stack keeps candidate indices in increasing or decreasing value order. When a new value makes earlier candidates irrelevant, they are popped permanently. A monotonic deque keeps useful candidates for a moving window and removes expired indices from the front.
How to approach it
Store indices when boundaries or duplicates matter; define whether equal values should be kept or removed.
Complexity
Each index is pushed and popped at most once, giving O(n) total time.
C# example
var candidates = new Stack<int>();
for (int i = 0; i < values.Length; i++)
{
while (candidates.Count > 0 && values[candidates.Peek()] < values[i])
nextGreater[candidates.Pop()] = i;
candidates.Push(i);
}
Expected result or behavior
Each popped index has found its first greater value to the right.
Practice exercise
Adapt the condition to find the next greater-or-equal element and test duplicates.
Key takeaway: Amortized analysis explains why nested push/pop loops can still be linear.