Show problems as
Classic problem #2454HardArrayBinary SearchStackSortingHeap (Priority Queue)Monotonic Stack

Next Greater Element IV

Real-world version: The Second Taller Mast Ahead
Tracked in this browser only
Read Next Greater Element IV on LeetCode(opens in a new tab)

The 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.

Python
def second_greater_element(nums: list[int]) -> list[int]:
Java
public int[] secondGreaterElement(int[] nums)