Next Greater Element II Visualizer & Step-by-Step Algorithm Solution

Find the next greater numeric element for every number in a circular integer array using a monotonic decreasing stack over two passes.

Category: stack | Difficulty: Medium

Tags: Stack, Monotonic Stack, Array, Circular Array

Next Greater Element II

nums (Pass 1 - Linear Scan)
1
0
2
1
1
2
result (Next Greater Element for each index)
-1
0
-1
1
-1
2
Push / Pop (Top)
(Empty Stack)
Monotonic Stack (Indices)
100%
state
i
i % n
pass
currentVal
stackSize0
n3
nums[1, 2, 1]
Initialization
1/36
Explanation

Start nextGreaterElements with array [1, 2, 1].

Source Code
1function nextGreaterElements(nums: number[]): number[] {
2 const n = nums.length;
3 const result = new Array(n).fill(-1);
4 const stack: number[] = []; // stores indices
5 for (let i = 0; i < 2 * n; i++) {
6 const num = nums[i % n];
7 while (stack.length && nums[stack[stack.length - 1]] < num) {
8 const poppedIdx = stack.pop()!;
9 result[poppedIdx] = num;
10 }
11 if (i < n) {
12 stack.push(i);
13 }
14 }
15 return result;
16}