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 is2 - For
nums[1] = 2: no greater element exists, so-1 - For
nums[2] = 1: searching circularly, we find2at 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
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
โ Quadratic Growth
Space Complexity
O(1)
Only using constant extra space for variables, not counting the output array
โ Linear Space
Constraints
- 1 โค nums.length โค 104
- -109 โค nums[i] โค 109
- The array is treated as circular
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code