Given an array of non-negative integers, your task is to find the second greater element for each number in the array.
The second greater element of nums[i] is the first element to the right that is greater than nums[i], but with exactly one greater element between them.
More formally, nums[j] is the second greater element of nums[i] if:
j > i(appears after the current element)nums[j] > nums[i](is greater than current element)- There exists exactly one index
kwherei < k < jandnums[k] > nums[i]
If no such element exists, return -1 for that position.
Example: In array [1, 2, 4, 3], the second greater element of 1 is 4 (with 2 as the first greater), and for 2 it's 3 (with 4 as the first greater).
Input & Output
Visualization
Time & Space Complexity
Single pass through array, each element is pushed and popped from stacks at most once
Space for result array and two monotonic stacks, each can hold at most n elements
Constraints
- 1 ≤ nums.length ≤ 104
- 0 ≤ nums[i] ≤ 109
- Follow up: Could you find an O(n) time solution?