Given a circular integer array nums (the element after the last is the first), return the next greater number for every element — the first strictly greater value encountered when moving forward and wrapping around. If none exists, use -1.
<= instead of <, so equal values also resolve pending indices.Input: nums = [1,2,1] Output: [2,-1,2] The last 1 wraps around to find 2; the 2 has no greater element.
Input: nums = [1,2,3,4,3] Output: [2,3,4,-1,4] The last 3 wraps around to find 4; the 4 finds nothing greater.
- 1 <= nums.length <= 10^4 - -10^9 <= nums[i] <= 10^9
It's the next-greater-element problem on a circular array. The monotonic-stack template still applies — you just walk the indices twice (using i % n) so an element can find a greater value that lies earlier in the array by wrapping around.
i % n to wrap the scan past the end of the array.“How far can I wrap?”
At most once around — every other element is reachable within n - 1 steps.
“Strict greater?”
Yes — an equal value doesn't count.
This is next-greater-element, but the array wraps, so an element can be answered by something earlier in the array.
I run the monotonic stack over 2n indices using i mod n, pushing real indices only in the first pass.
When a larger value arrives, it resolves every smaller index still on the stack.
Worked example — nums = [1, 2, 1]
i=0 (1): push 0 stack [0] i=1 (2): 2 > nums[0]=1 -> res[0]=2, pop; push 1 stack [1] i=2 (1): push 2 stack [1,2] i=3 (1%3=0 -> nums=1): no pop i=4 (1): no pop i=5 (2): 2 > nums[2]=1 -> res[2]=2, pop stack [1] answer: [2, -1, 2]
Scanning 2n indices with i % n lets an element be resolved by a greater value that appears earlier in the array, exactly what circularity allows.
Adding indices again in the second pass would double-count; the second pass only resolves pending indices.
Each index is pushed once and popped at most once across the doubled loop, so it's linear.
| Wrap-and-scan | Monotonic stack (2n) | |
|---|---|---|
| Idea | For each i, scan up to n-1 steps with modulo | Decreasing-value index stack over 2n indices |
| Time | O(n^2) | O(n) |
| Space | O(1) | O(n) |
Full code is in the Approaches selector below.
Key takeaway
Circular next-greater-element = the monotonic index stack run over 2n positions with i % n. Push indices only in the first pass; a larger incoming value resolves all smaller indices on the stack. O(n).
res = [-1]*n; stack = []
for i in 0 .. 2n-1:
while stack and nums[stack.top] < nums[i % n]:
res[stack.pop()] = nums[i % n]
if i < n: stack.push(i)
return res