visual walkthrough
Next Greater Element II
Handles a circular array by iterating twice.
The idea
It's the "next greater element" stack again, but on a circle: after the end, you wrap back to the start. Unrolling the array twice makes the circle a straight line.
Only the first pass pushes; the second pass just lets leftover waiting numbers find a bigger one that wrapped around.
Complexity
| approach | time | space |
|---|---|---|
| Walk the circle | O(n²) | O(1) |
| Stack, two passes | O(n) | O(n) |