Next Greater Element II Visualization & Animation
Finds next greater elements in a circular array by iterating twice with modulo and a monotonic stack; O(n).
## What is it?
Same as Next Greater Element I but the array is treated as **circular** — after the last element, wrap around to the beginning. Find the next greater element for each position in this circular array.
## How it works
- Iterate twice through the array (indices 0 to 2n-1) using modulo to simulate circularity
- Use a monotonic decreasing stack of indices
- On the first pass, build the stack normally
- On the second pass, pop elements from the stack whose next greater is found in the "wrap-around" portion
- Elements still in the stack after both passes have no greater element → -1
## When to use
- Circular arrays where the search wraps around
- Extension practice for the basic Next Greater Element problem
## Key Points
- The double-pass trick `(i % n)` simulates circularity without duplicating the array
- O(n) time, O(n) space
- Only need at most 2n iterations because after a full extra loop no new greater elements can be found
Category: algorithms
Difficulty: intermediate
Time Complexity: O(n)
Space Complexity: O(n)
View Next Greater Element II Visualization