Next Greater Element
Problem Given an array, find the next greater element for each entry — the first element to its right that is strictly greater than it. If no such element exists, output -1 for that position.
Input / Output
- Input: an array nums of integers.
- Output: an array of the same length where index i holds the next greater element of nums[i], or -1.
Constraints
- 1 <= nums.length <= 10^5, so the O(n^2) nested scan will time out.
- Values may repeat; "greater" is strict, so an equal value does not qualify.
- Circular variant: the search wraps past the end back to the start.
Example
- [4,5,2,25] -> [5,25,25,-1]
- Tricky case: a strictly decreasing array [5,4,3] -> [-1,-1,-1]; every element is pushed and none is ever popped, so the stack drains only at the end.
asked …