Next Greater Element II - Problem

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.

Input & Output

Example 1 — Basic Circular Array
$ Input: nums = [1,2,1]
Output: [2,-1,2]
💡 Note: For nums[0]=1, next greater is 2. For nums[1]=2, no greater element exists (-1). For nums[2]=1, wrapping around, next greater is 2.
Example 2 — All Elements Have Next Greater
$ Input: nums = [1,2,3,4,3]
Output: [2,3,4,-1,4]
💡 Note: nums[0]=1→2, nums[1]=2→3, nums[2]=3→4, nums[3]=4 has no greater (-1), nums[4]=3 wraps to find 4.
Example 3 — Single Element
$ Input: nums = [5]
Output: [-1]
💡 Note: Only one element, no next greater element possible in circular array.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Next Greater Element II - Circular Array Problem121Next: 2Next: -1Next: 2Input: [1,2,1]Output: [2,-1,2]Circular: last element can find next greater by wrapping to beginning🎯 Key Insight: Use monotonic stack with double iteration for O(n) solution
Understanding the Visualization
1
Input
Circular array [1,2,1] where last connects to first
2
Process
For each element, find next greater circularly
3
Output
Result [2,-1,2] showing next greater for each position
Key Takeaway
🎯 Key Insight: A monotonic stack processes each element at most twice to efficiently find next greater elements in circular arrays
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
180.0K Views
Medium Frequency
~15 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen