noodleProblems/
Next Larger Element
#116

Next Larger Element

AlgorithmmediumArrayStackMonotonic Stack

Given an integer array nums, return an array answer of the same length where answer[i] is the **next larger element** to the right of nums[i].

The next larger element of nums[i] is the first value that appears *after* index i and is strictly greater than nums[i]. If no such value exists, answer[i] is -1.

Example cases

  • mixed
    in nums = [2,1,2,4,3]
    out [4,2,4,-1,-1]
    2 is answered by the later 4; 1 by the 2 to its right; 4 and the trailing 3 have nothing larger ahead.
  • decreasing
    in nums = [5,4,3,2,1]
    out [-1,-1,-1,-1,-1]
    Every element is larger than everything to its right, so none has a next-larger.
  • increasing
    in nums = [1,3,2,4]
    out [3,4,4,-1]

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Saved
nums =
[2,1,2,4,3]