Next Greater Element

Given an integer array nums, return an array where answer[i] is the first element to the right of nums[i] that is strictly greater than nums[i]. If no such element exists, put -1. Example: Input: nums = [2,1,2,4,3] Output: [4,2,4,-1,-1] Explanation: For 2 at index 0, the next greater element is 4. For 1, it is 2. Pattern focus: Monotonic Decreasing Stack for Next Greater.

Input Format

nums = array of integers

Output Format

answer[i] = next greater value to the right, or -1 if none exists

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Examples

Example 1:

Input:

nums = [2,1,2,4,3]

Output:

[4,2,4,-1,-1]

Explanation:

Scan from left to right while maintaining a decreasing stack of unresolved values.

Example 2:

Input:

nums = [1,3,4,2]

Output:

[3,4,-1,-1]

Explanation:

Each number resolves earlier smaller values until the stack becomes decreasing again.

Loading...
Next Greater Element - Monotonic Stack Queue