A monotonic stack is a stack that maintains its elements in strictly increasing or decreasing order. Learn how to use it to find the next greater element for every element in an array.
Use a monotonic decreasing stack: iterate from right to left. For each element, pop all stack elements that are smaller (they cannot be the next greater). The top of the stack is the next greater element.
- Initialize result[] with -1.
- Iterate i from n-1 to 0.
- While stack is non-empty and stack.top() <= nums[i]: pop.
- If stack is non-empty: result[i] = stack.top(). Push nums[i].
- Time Complexity: O(N) — each element pushed and popped at most once
- Space Complexity: O(N)