Next Greater Element II solution explained
Next Greater Element II asks, for each number in a circular array, for the first strictly larger number you meet walking forward and wrapping around, or -1 if there is none. Walk the indexes twice with a stack of positions still waiting for an answer: each new value resolves every waiting position with a smaller value, and only the first lap pushes. Every index is pushed once and popped at most once, so it is O(n).
By Evin JohnPublished 6 min read
The problem in plain words
Imagine the numbers written around a circle. For each one, walk clockwise and stop at the first number strictly bigger than where you started. Report that number. If you come all the way around without finding one, report -1. The largest value always gets -1, and so does any value tied with it.
| Array | Answer | Note |
|---|---|---|
[3, 8, 4, 1, 2] | [8, -1, 8, 2, 3] | The last 2 wraps around to find the 3 |
[2, 7, 7, 1] | [7, -1, -1, 2] | Both 7s are the maximum |
[6, 4, 9, 9, 3] | [9, 9, -1, -1, 6] | The 3 at the end wraps to the 6 |
[5, 5, 5] | [-1, -1, -1] | Equal is not greater |
[9] | [-1] | Nothing else on the circle |
Why it gets asked
It is the circular twist on the classic next-greater-element pattern. If you already know the stack approach from Daily Temperatures, the interviewer wants to see how you handle the wrap without doubling memory, and whether you can explain why the second lap must not push.
Brute force: walk around from each element
def next_bigger_circular_slow(nums):
n = len(nums)
result = [-1] * n
for i in range(n):
for step in range(1, n):
j = (i + step) % n
if nums[j] > nums[i]:
result[i] = nums[j]
break
return resultStack of waiting indexes, two laps
Keep a stack of indexes whose answer is not known yet. When a value arrives, it is the answer for every waiting index with a smaller value, and those sit on top of the stack: everything still waiting has a value at least as big as everything pushed after it, so values never increase going up. Pop while the top is smaller, recording the current value, then push the current index.
For the circle, run k from 0 to 2n - 1 and use index k mod n. The first lap does the ordinary job. The second lap gives every element still waiting at the end of the array a chance to meet the elements before it. During the second lap you only pop, never push: each index needs only one entry, and pushing again would just repeat work and double the stack.
def next_bigger_circular(nums):
n = len(nums)
result = [-1] * n
waiting = [] # indexes with no answer yet; values never increase upward
for k in range(2 * n): # second lap lets the end see the start
value = nums[k % n]
while waiting and nums[waiting[-1]] < value:
result[waiting.pop()] = value
if k < n:
waiting.append(k) # only the first lap adds new indexes
return resultfunction nextBiggerCircular(nums) {
const n = nums.length;
const result = new Array(n).fill(-1);
const waiting = [];
for (let k = 0; k < 2 * n; k++) {
const value = nums[k % n];
while (waiting.length && nums[waiting[waiting.length - 1]] < value) {
result[waiting.pop()] = value;
}
if (k < n) waiting.push(k);
}
return result;
}Trace on the first example
[3, 8, 4, 1, 2]. First lap: push 0 (3). The 8 pops index 0 (answer 8), push 1. Push 2 (4), push 3 (1). The 2 pops index 3 (answer 2), push 4. The stack now holds indexes 1, 2, 4 with values 8, 4, 2. Second lap: the 3 pops index 4 (answer 3), then stops at the 4. The 8 pops index 2 (answer 8), then stops at the other 8, which is index 1 itself. The rest of the lap changes nothing, and index 1 keeps -1.
Why it is linear
The loop runs 2n times. Pushes happen only on the first lap, so there are n of them, and each index can be popped at most once. All the inner while loops together therefore do at most n pops. Total work is O(n), with O(n) space for the stack and the output.
| Approach | Time | Extra space |
|---|---|---|
| Walk around from each element | O(n²) | O(1) beyond the output |
| Concatenate the array with itself, then a normal stack pass | O(n) | O(n) for the copy and the stack |
| Two laps with modulo | O(n) | O(n) for the stack |
Edge cases
- Empty array: return an empty list; the loop never runs.
- One element: -1.
- All equal: all -1, because the pop condition is strictly less than.
- Several copies of the maximum: every copy gets -1, and the stack keeps them until the end.
- Negative numbers: nothing changes, since -1 is a marker in the output, not a value you compare against.
Mistakes that come up
- Pushing on the second lap too. It does not change the answers here, but it doubles the stack and the work, and it makes the code harder to reason about in variants.
- Using less-than-or-equal when popping, so equal values count as greater.
- Initializing results to 0 instead of -1, or using -1 both as "no answer" and as an array value in a comparison.
- Storing values on the stack instead of indexes, which leaves no way to write the answer to the right slot.
Follow-up ideas
- Return the distance instead of the value. When you pop an index, store k minus that index. Because k keeps counting through the second lap, the wrap is already included.
- Previous greater element on a circle. Walk the two laps from right to left.
- Next smaller element. Flip the comparison so the stack keeps values non-decreasing.
How to explain it out loud
Fictional example
- Candidate
- Without the circle this is next greater element: a stack of indexes still waiting, and each new value resolves every smaller one on top.
- Candidate
- For the wrap I'll loop over 2n positions with modulo. The second lap only resolves; it doesn't push, so each index is handled once.
- Candidate
- Each index is pushed once and popped at most once, so it's linear, and anything still on the stack at the end gets -1.
Related problems
132 Pattern runs a similar stack from the right to remember a middle value. Max Chunks To Make Sorted uses a stack of chunk maxima for its harder version, and Largest Rectangle in Histogram applies next-smaller logic on both sides. More on the coding problems hub.
How Natively fits into practice
On a Mac or a Windows PC, Natively can read the circular prompt from a screenshot while you practice and explain the no-push second lap, or step through your trace with you. The transcript of the session is saved, so you can replay how you described the amortized bound. More on the AI interview assistant page.
Questions people ask
How do you solve Next Greater Element II?
Loop over 2n positions using index modulo n, with a stack of indexes still waiting. Each value pops and answers every waiting index with a smaller value. Push only during the first lap; anything left gets -1.
Why loop twice in Next Greater Element II?
The array is circular, so elements near the end may find their answer among elements at the start. The second lap lets them see those elements without copying the array.
What is the time complexity of Next Greater Element II?
O(n) time and O(n) space. The loop runs 2n times, but each index is pushed once and popped at most once.
What does Next Greater Element II return for the maximum value?
-1. No value on the circle is strictly greater, and equal values do not count.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
