Next Greater Element II

medium

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.

Hints

It's next-greater-element, but the array wraps around.
Iterate 2n indices using i % n so elements can find greater values that wrap.
Keep an index stack decreasing by value; push only during the first pass.

Common doubts

A single pass can't let an early element find a greater value that appears earlier in the array. A second pass over the same indices (via i % n) covers the wrap-around.
The elements are already on the stack after the first pass. The second pass exists only to resolve them, not to add duplicates.
You need to write the answer at the correct position when an element is resolved, so the stack holds indices.

Interview follow-ups

Pop with <= instead of <, so equal values also resolve pending indices.
Mirror it: iterate 2n from the right (or reverse the roles), keeping the same decreasing index stack.

Fun facts

  • The 'process 2n with modulo' trick turns any linear array-scan into a circular one — used for circular subarray sums too.
  • This is the same monotonic stack as the linear version; only the loop bound and indexing change.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: nums = [1,2,1]
Output: [2,-1,2]
The last 1 wraps around to find 2; the 2 has no greater element.
Example 2
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.
Constraints

- 1 <= nums.length <= 10^4 - -10^9 <= nums[i] <= 10^9

Solve this problem →