1711. Second Taller Ahead

Hard7.5 points estimatedMonotonic StackStackArray

A film crew lines actors up for a group photo, and nums[i] is the height of the actor standing at position i of the row. Every actor wants to locate the second strictly taller actor somewhere to their right: look right, find the nearest actor who is strictly taller, then keep looking for the next actor who is also strictly taller than the original one. For each position i, return the index of that second strictly taller actor, or -1 if fewer than two taller actors stand to the right of i. The result is an int array with one entry per position of nums. The row has 1 to 100000 actors and heights between 0 and 10^9. Aim for O(n) time and O(n) extra space by sweeping left to right with two monotonic stacks: one for actors still waiting for their first taller partner and one for those waiting for their second.

Example 1

Input:
nums = [2,4,0,9,6]
Output:
[3,4,4,-1,-1]
Explanation:

For 2 the taller actors are 4 (index 1) and 9 (index 3), so the answer is 3; for 4 they are 9 and 6, so 4; for 0 they are 9 and 6, so 4; the last two have none.

Example 2

Input:
nums = [3,3]
Output:
[-1,-1]
Explanation:

Equal heights are not strictly taller, so nobody finds even one taller actor.

Example 3

Input:
nums = [1,2,3,4]
Output:
[2,3,-1,-1]
Explanation:

Index 0 sees 2 then 3 (answer 2), index 1 sees 3 then 4 (answer 3), and the last two have too few taller actors.

Constraints

1 ≤ n ≤ 105

0 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…