Second Greater Element

Given an integer array nums, return an array answer where answer[i] is the second greater element to the right of nums[i]. The second greater element is the second element to the right that is strictly greater than nums[i]. If it does not exist, put -1. Example: Input: nums = [2,4,0,9,6] Output: [9,6,6,-1,-1] Explanation: For 2, the first greater is 4 and the second greater is 9. Pattern focus: Next Greater Pattern with two-stage monotonic stacks.

Input Format

nums = array of integers

Output Format

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

Constraints

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

Examples

Example 1:

Input:

nums = [1,2,3,4]

Output:

[3,4,-1,-1]

Explanation:

The second greater element is the second strictly larger value to the right.

Example 2:

Input:

nums = [2,4,0,9,6]

Output:

[9,6,6,-1,-1]

Explanation:

The first greater and second greater may be different values for the same index.

Loading...
Second Greater Element - Monotonic Stack Queue