Circular Array (Ring Buffer)

Next Greater Element II

Medium
Solve it on LeetCode ↗

The problem

For each element of a CIRCULAR array, find the next greater element scanning forward (wrapping around), or −1.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Initialize answers to −1 and an empty stack of indices.
  2. 2Loop i from 0 to 2n − 1 with j = i % n.
  3. 3While the stack top’s value < nums[j], pop it and record nums[j] as its answer.
  4. 4Push j onto the stack only during the FIRST pass (i < n) — the second pass only resolves, never adds.

Key insight

Virtually doubling the array with modulo indexing simulates the wrap without copying — and pushing only in the first pass prevents duplicate resolution.

The solution

Watch out for

  • Pushing during the second pass double-processes indices — guard with i < n.
  • The maximum element correctly stays −1; no special-casing needed.