Next Greater Element II - Problem

Given a circular integer array nums, your task is to find the next greater element for every element in the array. Think of the array as a circle where the last element connects back to the first element!

The next greater element of a number x is the first number greater than x that appears when you traverse the array in order, searching circularly. If no such greater element exists, return -1 for that position.

Example: For array [1, 2, 1], the next greater elements are [2, -1, 2] because:

  • For nums[0] = 1: next greater is 2
  • For nums[1] = 2: no greater element exists, so -1
  • For nums[2] = 1: searching circularly, we find 2 at index 1

Input & Output

example_1.py โ€” Basic circular array
$ Input: [1, 2, 1]
โ€บ Output: [2, -1, 2]
๐Ÿ’ก Note: For index 0 (value 1): next greater is 2 at index 1. For index 1 (value 2): no greater element exists. For index 2 (value 1): searching circularly, next greater is 2 at index 1.
example_2.py โ€” All same elements
$ Input: [1, 1, 1, 1]
โ€บ Output: [-1, -1, -1, -1]
๐Ÿ’ก Note: Since all elements are the same, no element has a next greater element, so all results are -1.
example_3.py โ€” Decreasing sequence
$ Input: [5, 4, 3, 2, 1]
โ€บ Output: [-1, 5, 5, 5, 5]
๐Ÿ’ก Note: For index 0 (value 5): no greater element. For all other indices: the next greater element is 5 (wrapping around to index 0).

Visualization

Tap to expand
1index 02index 11index 2StackIndices waiting fornext greater elementResult2-12ProcessResolve๐ŸŽฏ Key: Process array twice, stack maintains decreasing order
Understanding the Visualization
1
Initialize Stack
Start with an empty stack to track indices of unresolved elements
2
Process Twice
Go through the array twice (2n iterations) to simulate circular nature
3
Pop and Resolve
When we find a larger element, resolve all smaller pending elements in the stack
4
Push New Index
Add current index to stack only in first pass to avoid duplicates
Key Takeaway
๐ŸŽฏ Key Insight: The monotonic stack approach efficiently solves the circular next greater element problem by processing the array twice while maintaining a decreasing stack of indices, achieving optimal O(n) time complexity.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ)

For each of the n elements, we potentially search through all n elements in the worst case

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using constant extra space for variables, not counting the output array

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • -109 โ‰ค nums[i] โ‰ค 109
  • The array is treated as circular
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
47.0K Views
High Frequency
~15 min Avg. Time
1.6K 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