InferenceAI

Enter at least two characters to search.

Start free

Next Greater Values

mediumStack25 min25 XP

For each element of nums, return the first value to its right that is strictly greater, or -1 if none exists.

Requirements

  • O(n)O(n) with a monotonic stack.

Examples

EXAMPLE WALKTHROUGHmixed

A guided view of the published example, not a trace of your code.

INPUT[[4,5,2,25]]
TASKnext_greater_values()
EXPECTED OUTPUT[5,25,25,-1]

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [4,5,2,25]

Output: [5,25,25,-1]

Explanation: mixed

Input: nums = [13,7,6,12]

Output: [-1,12,12,-1]

Explanation: later larger

Input: nums = [3,2,1]

Output: [-1,-1,-1]

Explanation: decreasing

Hint 1

Keep a stack of indices whose answer is not known yet; values on it are decreasing.

Topics

DSAStackPython