Stacks and Queues Monotonic stack
212. Next Greater Element II
You are given an array of integers nums arranged in a circle: after the last value comes the first one
again.
For each position i, walk forward from i around the circle and look at the other values one by one. The
next greater element of nums[i] is the first of those values that is larger than nums[i]. An equal
value is not larger. The walk stops when it comes back to i, so if no other value is larger, the answer
is -1.
Return an array answer of the same length as nums, where answer[i] is the next greater element of
nums[i].
Example 1
Input: nums = [3, 8, 4, 1, 2]
[8,-1,8,2,3]Explanation: Nothing beats 8, so its answer is −1. The walk from 2 runs off the end and wraps to the 3 at the start. The walk from 4 passes 1, 2 and 3, which are all smaller, and stops at 8.
Example 2
Input: nums = [7, 7, 2, 7]
[-1,-1,7,-1]Explanation: An equal value is not larger, so every 7 gets −1. The first value after 2 is a 7, which is larger.
Example 3
Input: nums = [10, 6, 0]
[-1,10,10]Explanation: The values fall from left to right, so 6 and 0 both have to wrap around to find the 10 at the start.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 1050 ≤ nums[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.