Next Greater Element II (LeetCode 503): Solution and Explanation
For each element of a circular array, find the first value that is strictly larger when you move forward, wrapping from the end back to the start. If no such value exists anywhere, the answer for that element is -1.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force answer looks ahead from every index, up to n - 1 steps with wraparound, until it finds something larger. That is O(n²), and on an array like [5,4,3,2,1] most of those scans run the full length.
The non-circular version of this problem has a well known linear solution: a monotonic stack of indices still waiting for their answer. As you scan, each new value resolves every waiting index whose value is smaller, because it is the first larger value they have met. Those indices are popped and filled in. The ones left on the stack always have decreasing values from bottom to top, since any smaller value sitting above a larger one would already have been resolved.
The circular part sounds harder than it is. Wrapping around just means that elements near the end can find their answer near the start. If you scan the array twice, using i % n to read values, then every element sees every other element after it in circular order. During the second pass you only resolve waiting indices; you do not push anything new, because each index already had its turn to wait in the first pass.
Indices still on the stack after both passes have no larger value anywhere in the array, which in practice means they hold the maximum, and their answer stays at the default -1.
Approach: Monotonic stack over a doubled scan
- Set
n = len(nums), fillresultwith -1, and create an emptystackof indices. - Loop
ifrom 0 to2 * n - 1and map it into the array withidx = i % n. - While the stack is not empty and
nums[stack[-1]] < nums[idx], pop the index and set its result tonums[idx]. - Only during the first pass, when
i < n, pushionto the stack so it waits for a larger value. - After the loop, return
result. Anything never resolved keeps its -1.
Step-by-step example
nums = [1,2,1]
- i = 0 reads 1. The stack is empty, so index 0 is pushed. The stack is [0].
- i = 1 reads 2, which is larger than
nums[0] = 1, soresult[0] = 2and index 0 is popped. Index 1 is pushed, giving [1]. - i = 2 reads 1, which is not larger than 2, so index 2 is pushed. The stack is [1,2].
- i = 3 wraps to index 0 and reads 1. It is not larger than
nums[2] = 1, and since i is at least n nothing is pushed. - i = 4 wraps to index 1 and reads 2, which beats
nums[2] = 1, soresult[2] = 2. It does not beatnums[1] = 2, so the loop stops. - i = 5 reads 1 and changes nothing. Index 1 never resolves, so the answer is [2,-1,2].
Code: Python, Java, C++
1class Solution:
2 def nextGreaterElements(self, nums: List[int]) -> List[int]:
3 n = len(nums)
4 result = [-1] * n
5 stack = [] # stores indices
6
7 # Iterate twice to handle circular array
8 for i in range(2 * n):
9 idx = i % n
10 while stack and nums[stack[-1]] < nums[idx]:
11 result[stack.pop()] = nums[idx]
12 if i < n:
13 stack.append(i)
14 return result1class Solution {
2 public int[] nextGreaterElements(int[] nums) {
3 int n = nums.length;
4 int[] result = new int[n];
5 Arrays.fill(result, -1);
6 Stack<Integer> stack = new Stack<>();
7
8 for (int i = 0; i < 2 * n; i++) {
9 int idx = i % n;
10 while (!stack.isEmpty() && nums[stack.peek()] < nums[idx]) {
11 result[stack.pop()] = nums[idx];
12 }
13 if (i < n) {
14 stack.push(i);
15 }
16 }
17 return result;
18 }
19}1class Solution {
2public:
3 vector<int> nextGreaterElements(vector<int>& nums) {
4 int n = nums.size();
5 vector<int> result(n, -1);
6 stack<int> stk;
7
8 for (int i = 0; i < 2 * n; i++) {
9 int idx = i % n;
10 while (!stk.empty() && nums[stk.top()] < nums[idx]) {
11 result[stk.top()] = nums[idx];
12 stk.pop();
13 }
14 if (i < n) {
15 stk.push(i);
16 }
17 }
18 return result;
19 }
20};Time and space complexity
O(n)
The loop runs 2n times, and each index is pushed once and popped at most once, so the total stack work is linear.
O(n)
The stack can hold all n indices, for example when the array is strictly decreasing, and the result array has n entries.
Other approaches
Brute force circular scan (time O(n²), space O(1))
For each index, step forward through (i + j) % n for j from 1 to n - 1 and stop at the first larger value. It is simple and uses no extra structure, but strictly decreasing inputs make it quadratic.
Right to left stack of values (time O(n), space O(n))
Scan the doubled range from the right, popping values that are not larger than the current one, and read the answer from the top of the stack. It produces the same results and suits people who think of the stack as a list of candidates.
Common mistakes
- Pushing
iduring the second pass as well. Those values ofiare at least n, so a later pop would try to writeresult[i]past the end of the array. - Using
<=instead of<when popping. The problem asks for a strictly greater value, so equal elements must not resolve each other. - Storing values instead of indices on the stack, which leaves you no way to know where to write the result.
- Scanning only once and forgetting the wraparound, which gives -1 for elements whose answer lies at the start of the array.
Frequently asked questions
Why do we loop through the array twice?
In a circular array the next greater value for an element near the end may be near the beginning. A second pass lets every waiting index see the elements that come before it in the original order, which is what wrapping around means.
Why does the stack hold indices instead of values?
When a larger value arrives, you need to know which positions in result to fill. Indices give you that, and you can always read the value with nums[index].
Which elements end up with -1?
Only elements equal to the array's maximum. Every other element has a strictly larger value somewhere in the array, and the two-pass scan will always reach it.