LeetCode #503 Medium

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.
Constraints
  • 1 <= nums.length <= 10⁴
  • -10⁹ <= nums[i] <= 10⁹
monotonic-stackarray
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def nextGreaterElements(self, nums: list[int]) -> list[int]:
▶3 n = len(nums)
▶4 res = [-1] * n
▶5 stack = []
▶6 for i in range(2 * n):
▶7 x = nums[i % n]
▶8 while stack and nums[stack[-1]] < x:
▶9 res[stack.pop()] = x
▶10 if i < n:
▶11 stack.append(i)
▶12 return res
two laps1#02#11#2waiting (stack)answer#0#1#2nobody has an answer yet
n3
Every answer starts as −1 and the stack is empty. The ring is read clockwise from #0, twice: the second lap is how the last elements get to look at the first ones.
lap 1 of 21#02#11#2waiting (stack)1#0answer#0#1#21 joins the stack to wait
i0
x1
waiting1
The stack was empty, so #0 goes on the stack to wait for a larger value that may come later, or after the wrap.
lap 1 of 21#02#11#2waiting (stack)answer2#0#1#22 beats 1 → #0 gets 2
i1
x2
answer #02
The waiting value 1 (#0) is smaller than 2. Nothing between them was larger, or it would have popped #0 first, so 2 is its next greater element.
lap 1 of 21#02#11#2waiting (stack)2#1answer2#0#1#22 joins the stack to wait
i1
x2
waiting1
Nothing is left waiting, so #1 goes on the stack to wait for a larger value that may come later, or after the wrap.
lap 1 of 21#02#11#2waiting (stack)2#11#2answer2#0#1#21 joins the stack to wait
i2
x1
waiting2
The value under it, 2, is not smaller than 1, so the pops stop. #2 goes on the stack to wait for a larger value that may come later, or after the wrap.
lap 2 of 21#02#11#2waiting (stack)2#11#2answer2#0#1#2lap 2: 1 answers nobody
i3
x1
waiting2
On the second lap #0 is only read, not pushed again. The top of the stack, 1, is not smaller than 1, so nobody gets an answer here.
lap 2 of 21#02#11#2waiting (stack)2#1answer2#0#12#22 beats 1 → #2 gets 2
i4
x2
answer #22
Second lap, so #1 is being read again. The waiting value 1 (#2) is smaller than 2. Nothing between them was larger, or it would have popped #2 first, so 2 is its next greater element.
lap 2 of 21#02#11#2waiting (stack)2#1answer2#0#12#2lap 2: 2 is not pushed again
i4
waiting1
#1 is already on the stack or answered from the first lap, so the second lap only uses it to answer others. 2 on top is not smaller, so the pops stop.
lap 2 of 21#02#11#2waiting (stack)2#1answer2#0#12#2lap 2: 1 answers nobody
i5
x1
waiting1
On the second lap #2 is only read, not pushed again. The top of the stack, 2, is not smaller than 1, so nobody gets an answer here.
two laps1#02#11#2waiting (stack)2#1answer2#0−1#12#2done: 2, −1, 2
still waiting1
After two laps, #1 never met a larger value anywhere on the ring, so it keeps −1. The largest value always ends up here.
05

Common pitfalls

Stopping after one lap

✗ Wrong
for i in range(n):
✓ Right
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

✗ Wrong
while stack and nums[stack[-1]] <= x:
✓ Right
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].

06

Edge cases

A single element

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.

Negative values, where −1 can be a real answer

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.

07

Complexity

Time
O(n)
Space
O(n)
The loop runs 2n times. Each index is pushed once and popped at most once, so all the inner pops together add at most n steps. The stack and the answer list hold up to n entries each.
08

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.