All problems
0902HardArrayBinary SearchStackSortingHeap (Priority Queue)Monotonic Stack

The Second Taller Mast Ahead

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2454Next Greater Element IV

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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