Next Greater Element II (LeetCode 503): Solution and Explanation

Medium
Array
Stack
Monotonic Stack

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Set n = len(nums), fill result with -1, and create an empty stack of indices.
  2. Loop i from 0 to 2 * n - 1 and map it into the array with idx = i % n.
  3. While the stack is not empty and nums[stack[-1]] < nums[idx], pop the index and set its result to nums[idx].
  4. Only during the first pass, when i < n, push i onto the stack so it waits for a larger value.
  5. After the loop, return result. Anything never resolved keeps its -1.

Step-by-step example

nums = [1,2,1]
  1. i = 0 reads 1. The stack is empty, so index 0 is pushed. The stack is [0].
  2. i = 1 reads 2, which is larger than nums[0] = 1, so result[0] = 2 and index 0 is popped. Index 1 is pushed, giving [1].
  3. i = 2 reads 1, which is not larger than 2, so index 2 is pushed. The stack is [1,2].
  4. 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.
  5. i = 4 wraps to index 1 and reads 2, which beats nums[2] = 1, so result[2] = 2. It does not beat nums[1] = 2, so the loop stops.
  6. 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 result

Time and space complexity

Time

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.

Space

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 i during the second pass as well. Those values of i are at least n, so a later pop would try to write result[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.