LeetCode #503 Medium

Next Greater Element II

For each element in a circular array, find the next greater element, searching wrap-around; return -1 where none exists.

monotonic-stackarray
Open on LeetCode ↗
02

Intuition

💡

The trap is writing an answer on every visit to index i, including the first lap. Loop 2n times with i % n, and the first lap (when i >= n) is only there to preload the stack with elements from the front of the array — write to res[i] on that lap and you overwrite a correct answer with a partial one computed before the stack was full. The fix is a single guard: only record res[i] when i < n, the real, final lap.

03

Approach

1

Recall the linear monotonic stack

Walk right to left keeping a stack of candidates in decreasing order. Before reading the answer for i, pop everything at or below nums[i] — those can never be anyone's next greater element while nums[i] sits in front of them. Whatever remains on top is the answer, or -1 if the stack empties.

2

Handle the wrap with a double loop

Run i from 2n - 1 down to 0 and use nums[i % n]. By the time the index reaches the original range, the stack already holds the elements from the front of the array, so wrap-around lookups resolve naturally without duplicating the array in memory.

3

Only write answers on the real lap

During the first lap (i >= n) just maintain the stack — push and pop but record nothing. Once i < n, write res[i]. Drop the i < n guard and the code still runs and still looks plausible, because the loop only ever writes res[i % n] — but on the first lap the stack has not seen the whole array yet, so those early writes are wrong and get silently left in place if the real lap never overwrites the same slot correctly. Each element is pushed and popped at most twice, so the total is O(n) time and O(n) space.

04

Solution & live demo

python
1class Solution:
2 def nextGreaterElements(self, nums):
3 n = len(nums)
4 res = [-1] * n
5 st = []
6 for i in range(2 * n - 1, -1, -1):
7 cur = nums[i % n]
8 while st and st[-1] <= cur:
9 st.pop()
10 if i < n and st:
11 res[i] = st[-1]
12 st.append(cur)
13 return res
05

Edge cases

All elements equal

Strict > means nothing qualifies, so every answer is -1.

Strictly increasing array

The maximum gets -1 and everything else points to its right neighbour.

Single element

It cannot exceed itself, so the answer is [-1].

The maximum element

Always -1, since nothing anywhere in the circle is greater.

06

Complexity

Time
O(n)
Space
O(n)
2n iterations, each element pushed and popped a bounded number of times.