Next Greater Element II (circular)
Problem Statement
You get an array nums that is circular: after the last element, you continue from the first one again.
For each element, find its next greater number: the first number bigger than it that you meet while walking forward from it, wrapping around the end if needed. If no such number exists anywhere, the answer is -1.
An integer array nums (values can repeat and can be negative).
An array ans of the same length, where ans[i] is the next greater number of nums[i] going round the circle, or -1.
The first 1 sees 2 right away. 2 is the biggest, so -1. The last 1 wraps around to the start, passes 1, and finds 2.
The last 3 has nothing after it in a straight line, but wrapping around it meets 1, 2, then 4.
- • 1 ≤ nums.length ≤ 10^4
- • −10^9 ≤ nums[i] ≤ 10^9
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each i, check the next n − 1 positions using % n
Run the next-greater stack for i = 0 … 2n − 1 with nums[i % n]; push only in lap 1
For each index i, check positions (i+1) % n, (i+2) % n, … for n − 1 steps. The first bigger value is the answer. If none is found, it stays -1.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Monotonic Stack translate into production architectures and low-level memory mechanics.