Ctrl K

Second Larger to the Right

Hard
You get an array of non-negative integers values. For each element values[i], look at the elements to its right and list, in order, those strictly greater than values[i]. The second one in that list is the answer for position i. If there are fewer than two of them, the answer is -1. Return the array of answers, the same length as values.
Example 1
values=[3, 1, 5, 2, 7, 4] → [7, 2, -1, 4, -1, -1]

For 3 the larger values to its right are 5, then 7, so the answer is 7. For 1 they are 5, then 2: answer 2. 5 has only one larger value after it (7), so -1. For 2 they are 7, then 4: answer 4. Both 7 and 4 get -1.

Example 2
values=[6, 6, 6] → [-1, -1, -1]

Equal values do not count as larger, so every answer is -1.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 0 ≤ values[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBest Pair Above the Bars HardFirst Common Rooftop HardSorting Batches With Repeats HardWhen Rail Robots Catch Up HardWidest Fence Span Around the Marked Board Hard
loading Python…
Input
values=[3, 1, 5, 2, 7, 4]
Expected
[7, 2, -1, 4, -1, -1]

Run checks the first 3 tests in your browser. Submit checks all 226 tests on the server, hidden ones included.