Next Greater Element II
Next Greater Element II is LeetCode 503 (Medium). The array nums is circular: after the last element comes the first one again. For every element, return the first value larger than it that you meet when walking to the right and wrapping around. If no larger value exists anywhere in the array, the answer for that element is −1.
- Larger means strictly larger. An equal value is not an answer.
- With up to 10⁴ elements, checking every pair takes about 10⁸ steps, so a single linear sweep is expected.
- 1 <= nums.length <= 10⁴
- -10⁹ <= nums[i] <= 10⁹
Intuition
Without the wrap, this is the one-pass stack sweep: keep the indices that are still waiting for a larger value, and let each new value answer every smaller value waiting on the stack.
The circle adds one thing. An element near the end may find its answer near the start, after the sweep has already passed it. So walk the array twice. On the second lap every waiting index gets to see the elements in front of it again, which is exactly the wrap-around part it missed. Push indices only on the first lap, so each element waits once. An index still waiting after two laps has seen every other element, none of them larger, so it keeps −1.
"First larger (or smaller) value to the right" is a monotonic stack. The word circular, or "the next element of the last one is the first", means the same sweep run over the array twice.
Approach
Before reading on, take the plain next-greater sweep and ask which elements it leaves at −1 that should have an answer once the array wraps. How many more steps would those elements need to see everything? Aim for O(n) time.
Keep a stack of waiting indices
Fill res with −1 and start an empty stack. The stack holds indices whose next greater value is not known yet. Their values never increase from bottom to top, because anything smaller than a newcomer is answered and removed before the newcomer goes on.
Loop 2n times and read nums[i % n]
Let i run from 0 to 2n − 1 and take x = nums[i % n]. The remainder makes the second half of the loop a second lap over the same array, so there is no need to build a doubled copy.
Pop every smaller waiting value
While the value on top of the stack is smaller than x, pop that index and set its answer to x. It is the first larger value for that index: anything between the two that was larger would already have popped it.
Push only on the first lap
When i < n, push i. On the second lap every index has already been pushed once. A second copy would only meet the elements the first copy has already seen, so pushing it again is wasted work.
Indices left on the stack keep −1
After both laps, each index still on the stack has been compared with every other element and nothing was larger. The largest value in the array, and any copies of it, always end up here.
Code in Python, C++ and Java
Common pitfalls
Stopping after one lap
for i in range(n):
for i in range(2 * n):
One lap never lets the end of the array look at the start. For nums = [1, 2, 1] the last 1 is left at −1, but walking on from the end you reach 2 at the front. The correct output is [2, -1, 2].
Popping on equal values
while stack and nums[stack[-1]] <= x:
while stack and nums[stack[-1]] < x:
With <=, an equal value answers the one waiting on the stack. For nums = [2, 2] the first 2 gets 2 as its answer, but equal is not greater, so the output must be [-1, -1].
Edge cases
The loop visits it twice. On the second visit it meets itself on the stack, and since it is not smaller than itself it is not popped, so the answer is −1.
For nums = [-2, -1] the output is [-1, -1]: the first −1 is the value found, the second means none. The code never reads res to decide anything, so this mix-up cannot break it.
Complexity
Next Greater Element II FAQ
Why not loop over nums + nums instead?
It gives the same answers and some find it easier to read, but it allocates 2n values only to read each one twice. Reading nums[i % n] touches the same element without the copy.
Can the sweep run from right to left instead?
Yes. Run i from 2n − 1 down to 0 with a stack of values: pop everything not larger than nums[i % n], and when i < n the top of the stack (if any) is the answer. Then push the value. It is also O(n).
How is this different from Next Greater Element I?
In that problem (number 496) there is no wrap, the values are distinct, and you answer only for the values listed in a second array, so answers go in a map from value to answer. Here values can repeat, so answers are stored by index.