Next Greater Element II

Given a circular integer array nums, return an array where answer[i] is the next greater element of nums[i] when scanning to the right cyclically. If it does not exist, return -1. Example: Input: nums = [1,2,1] Output: [2,-1,2] Explanation: The array is circular, so the last 1 can still see the first 2. Pattern focus: Monotonic Decreasing Stack for Next Greater on Circular Arrays.

Input Format

nums = circular array of integers

Output Format

answer[i] = next greater value in circular order, or -1 if none exists

Constraints

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

Examples

Example 1:

Input:

nums = [1,2,1]

Output:

[2,-1,2]

Explanation:

A circular scan allows the last element to look back to the beginning.

Example 2:

Input:

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

Output:

[8,-1,8,2,3]

Explanation:

We simulate two passes to handle wrap-around.

Loading...
Next Greater Element II - Monotonic Stack Queue