Next Greater Element II
Problem
You are given a circular integer array nums: the element after the last one is the first one again. For every element, find the next greater element, meaning the first element with a strictly larger value that you reach by walking forward from it (wrapping around the end if needed). If no such element exists, report -1 for that position. Return the results as an array.
- The array has between 1 and 30,000 elements.
- Every value fits in a signed 32-bit integer; negatives are allowed.
Examples
nums = [4, 7, 4]→[7, -1, 7]. The last4wraps around to find the7at index 1; the7is the maximum and has no greater element.nums = [9, 6, 3, 8, 1]→[-1, 8, 8, 9, 9].6and3are answered by the8ahead of them;8and1wrap around to the9.nums = [6, 6, 6]→[-1, -1, -1]. Equal values are not "greater".
Hints
- Solve the non-circular version first: a stack of indices whose values are decreasing, popped whenever a larger value arrives.
- How far forward could you ever need to walk? At most one full lap.
- Run the same sweep over indices
0 .. 2n-1, mapping each toi % n, but only push indices during the first lap.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.