Monotonic stack · Medium
A metrics display annotates each reading with the closest earlier reading that was strictly lower. Looking back by scanning the entire history for every reading is too expensive for a long stream.
Return the nearest earlier index with a strictly smaller value for each input position.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[] }
Fields
- nums is an array of signed integers in its original order. Equal values at different indexes are separate entries.
Output
Return value
- Return one zero-based index per value. Use -1 when no earlier smaller reading exists.
- Equal values do not qualify. Choose the greatest qualifying earlier index, not the smallest value.
Constraints
- 0 <= nums.length <= 100000; -1000000000 <= nums[i] <= 1000000000.
- All requested totals and counts fit exactly in a safe JSON integer.
Examples
Example 1
{
"nums": [
2,
5,
5,
3
]
}Returns
[
-1,
0,
0,
0
]Example 2
{
"nums": [
1,
4,
2,
3
]
}Returns
[
-1,
0,
0,
2
]Required complexity
O(n) time and O(n) space