Next Greater Element II
Master this topic with zero to advance depth.
Next Greater Element II
Given a circular integer array nums, return the next greater number for every element. Circularly means after the last element, we search from the beginning.
Visual Representation
nums = [1, 2, 1]
Pass 1:
1. Index 0 (1): Stack [0]
2. Index 1 (2): 2 > 1. ans[0]=2. Pop 0, Push 1. Stack [1]
3. Index 2 (1): 1 < 2. Push 2. Stack [1, 2]
Pass 2 (Circular):
4. i=0 (1): 1 < 1 (top). Skip.
5. i=1 (2): 2 > 1 (top). ans[2]=2. Pop 2. Stack [1]
Final Result: [2, -1, 2]Examples
Level I: Brute Force (Double Pass Circular Scan)
Intuition
For each element, simulate the circular search by iterating up to 2N positions using modulo. When we find the first element greater than the current one, store the distance. This is straightforward but slower.
Level II: Circular Brute Force (Modulo Operator)
Intuition
Instead of two physical passes or flattening the array, we can use the modulo operator % to wrap around. For each element at index i, we check elements from (i+1) % n to (i + n - 1) % n. This is the same complexity as Level I but emphasizes the use of modular arithmetic for circular data structures.
Level III: Optimal (Monotonic Stack, Double Pass)
Intuition
To handle the circularity, we can conceptually concatenate the array with itself. In practice, we iterate from 0 to 2N-1 and use modulo i % N to access elements. A monotonic stack stores indices of elements looking for their next greater neighbor.
Detailed Dry Run
| i | i % N | Val | Stack | ans Update |
|---|---|---|---|---|
| 0 | 0 | 1 | [0] | - |
| 1 | 1 | 2 | [1] | ans[0]=2 |
| 2 | 2 | 1 | [1, 2] | - |
| 3 | 0 | 1 | [1, 2] | - |
| 4 | 1 | 2 | [1] | ans[2]=2 |
⚠️ Common Pitfalls & Tips
Modding i % n is essential for circular behavior. Only push to the stack in the first pass i < n to avoid infinite loops or duplicates.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.