Next Greater Element IV
Real-world version: The Second Taller Mast AheadThe statement here is our own: the same inputs, outputs and technique.
Mast heights along a line are given as nums.
For each mast, look rightwards for the masts strictly taller than it. Return the height of the second such mast, or -1 when fewer than two exist.
Return one answer per mast, in order.
Examples
Example 1
- Input
- nums = [13, 6, 19, 7, 21, 8]
- Output
- [21, 7, -1, 8, -1, -1]
For the mast of height 13, the taller masts ahead are 19 and 21, so the second is 21. For the 6, they are 19, 7, 21 and 8, so the second is 7. The last two masts have no second taller mast ahead.
Example 2
- Input
- nums = [1, 2, 3, 4, 5]
- Output
- [3, 4, 5, -1, -1]
Every mast is taller than the one before, so the second taller mast ahead is two places along, until the list runs out.
Example 3
- Input
- nums = [5, 5, 5, 5]
- Output
- [-1, -1, -1, -1]
No mast is strictly taller than any other, so none has an answer.
Constraints
- 1 <= nums.length <= 10^5
- 0 <= nums[i] <= 10^9
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def second_greater_element(nums: list[int]) -> list[int]:public int[] secondGreaterElement(int[] nums)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's