Skip to content

visual walkthrough

Next Greater Element II

Handles a circular array by iterating twice.

Solve on LeetCode

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

approachtimespace
Walk the circleO(n²)O(1)
Stack, two passesO(n)O(n)

More walkthroughs