Problem 267491 · easy · Phase 02 Linear Data Structures

Next Greater Value

stacks · monotonic stack

Given a list of integers nums, return a list res of the same length where res[i] is the first value to the right of nums[i] that is strictly greater than nums[i], or -1 if there is none.

Examples

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

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

Constraints

  • 0 <= len(nums) <= 10**5
  • -10**9 <= nums[i] <= 10**9
  • Target: O(n) time (the nested-loop solution is too slow for the largest inputs)

Goals

  • Keep a stack of indices still waiting for an answer
  • Resolve waiting indices when a larger value arrives
Starting Python…