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 INPUT Circular Array nums 1 i=0 2 i=1 1 i=2 Input Array: nums = [1, 2, 1] Length: 3 (circular) ALGORITHM STEPS 1 Initialize Stack Use stack for indices Result array = [-1,-1,-1] 2 Traverse 2x Length Loop i from 0 to 2*n-1 Use i % n for index 3 Pop Smaller Elements While stack not empty AND nums[top] < nums[i%n] 4 Update Result result[popped] = nums[i%n] Push current index Stack tracks indices 0 1 2 Monotonic decreasing FINAL RESULT For each element: nums[0] = 1 Next greater: 2 OK nums[1] = 2 No greater: -1 -1 nums[2] = 1 Circular: 2 OK OUTPUT [2, -1, 2] Complete! Key Insight: Use a monotonic decreasing stack and traverse the array twice (2*n iterations) to handle the circular nature. For each element, pop smaller elements from stack and update their next greater element. Time: O(n), Space: O(n). The second pass catches circular cases. TutorialsPoint - Next Greater Element II | Optimal Stack-Based Solution
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