Next Greater Element II

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Next Greater Element II

Approach

Use a monotonic decreasing stack of indices and iterate twice over the array using modulo arithmetic. The first pass pushes indices; both passes resolve next greater values by popping smaller elements.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Monotonic Stack (Circular Array)

Why It Works

Doubling traversal exposes wrap-around candidates while preserving nearest-right semantics. Each index is pushed once and popped once, so total work stays linear.

Updated Feb 2026