Monotonic stack · Medium
A monitoring tool annotates each reading with the next later reading that is strictly higher. It needs the first qualifying value in time order, not the largest value anywhere later.
Return the first strictly greater value to the right of each index or -1 when no such value exists.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "nums": number[] }.
Fields
- nums contains readings in their original order. Equal readings do not qualify as greater.
Output
Return value
- Return an array with the same length as nums, preserving index correspondence.
- Return the value rather than its index or distance. A real next value of -1 is allowed and shares the sentinel representation.
- Empty input returns [].
Constraints
- At most 100000 values, each an integer in [-1000000000,1000000000].
Examples
Example 1
{
"nums": [
2,
1,
3,
4
]
}Returns
[
3,
3,
4,
-1
]3 is the first higher value after 2, not 4.
Example 2
{
"nums": [
2,
2
]
}Returns
[
-1,
-1
]Equal values are not greater.
Required complexity
O(n) time and O(n) extra space