Next Greater Element II
Medium
Topics
Given a circular array nums, return an array where each position holds the next greater element (searching circularly), or -1 if none exists.
Example 1
Input: nums = [1,2,1] Output: [2,-1,2]
Example 2
Input: nums = [1,2,3,4,3] Output: [2,3,4,-1,4]
Constraints
- 1 <= nums.length <= 10^4
- -10^9 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls
Intuition
The non-circular version is the textbook monotonic stack: hold indices whose answer is still unknown, in decreasing order of value, and when a larger value arrives, pop and resolve everything it dominates.
Circularity is handled by walking 2n indices and reading nums[i % n]. The second lap gives every element a chance to be resolved by a value that sits before it in the original order. Indices are only pushed during the first lap, so each one resolves at most once.
Approach
- Fill the result with
-1, the answer for anything never resolved. - Walk
ifrom 0 to2n - 1, takingcur = nums[i % n]. - While the stack is non-empty and its top value is strictly less than
cur, pop it and writecurinto that slot. - Push
ionly whilei < n.
Dry Run
nums = [1,2,3,4,3]
i i%n cur pops stack(idx) res
0 0 1 - [0] [-1,-1,-1,-1,-1]
1 1 2 res[0]=2 [1] [ 2,-1,-1,-1,-1]
2 2 3 res[1]=3 [2] [ 2, 3,-1,-1,-1]
3 3 4 res[2]=4 [3] [ 2, 3, 4,-1,-1]
4 4 3 - [3,4] [ 2, 3, 4,-1,-1]
5 0 1 - [3,4] [ 2, 3, 4,-1,-1]
6 1 2 - [3,4] [ 2, 3, 4,-1,-1]
7 2 3 - [3,4] [ 2, 3, 4,-1,-1]
8 3 4 res[4]=4 [3] [ 2, 3, 4,-1, 4] <- the wrap-around resolution
9 4 3 - [3] [ 2, 3, 4,-1, 4]
answer [2,3,4,-1,4]Index 4 holds a 3 whose next greater element is the 4 at index 3 — reachable only by wrapping. Index 3 holds the maximum and stays -1, correctly, since the comparison is strict.
Complexity
- Time — O(n):
2niterations, and across all of them each index is pushed at most once and popped at most once. The innerwhileis amortised, not nested. - Space — O(n) for the stack. The result array is output and is conventionally excluded.
Common Pitfalls
- Using
<=instead of<when popping. On[1,1]that returns[1,1]instead of[-1,-1]: equal elements resolve each other, but "next greater" is strict. - Only one lap, which leaves every element whose answer wraps around at
-1. - Storing values on the stack instead of indices, which loses the slot to write the answer into.
- Misreading what the
i < nguard is for. Compared against the shown solution on every array up to length 6 over four distinct values, the no-guard version never diverges, so the guard is not protecting correctness here. It keeps each index resolved once and the stack at O(n) — defend it on those grounds, not as a bug fix. - Walking
3nor more laps "to be safe". Two laps suffice, because an element not resolved after seeing every other element once will never be resolved.
Full Solution — all languages
class Solution:
def nextGreaterElements(self, nums):
n = len(nums)
res = [-1] * n
stack = []
for i in range(2 * n):
cur = nums[i % n]
while stack and nums[stack[-1]] < cur:
res[stack.pop()] = cur
if i < n:
stack.append(i)
return resimport java.util.*;
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] res = new int[n];
Arrays.fill(res, -1);
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < 2 * n; i++) {
int cur = nums[i % n];
while (!stack.isEmpty() && nums[stack.peek()] < cur) res[stack.pop()] = cur;
if (i < n) stack.push(i);
}
return res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> nextGreaterElements(vector<int>& nums) {
int n = (int)nums.size();
vector<int> res(n, -1);
vector<int> stack;
for (int i = 0; i < 2 * n; i++) {
int cur = nums[i % n];
while (!stack.empty() && nums[stack.back()] < cur) {
res[stack.back()] = cur;
stack.pop_back();
}
if (i < n) stack.push_back(i);
}
return res;
}
};/**
* @param {number[]} nums
* @return {number[]}
*/ var nextGreaterElements = function(nums) {
const n = nums.length;
const res = new Array(n).fill(-1);
const stack = [];
for (let i = 0; i < 2 * n; i++) {
const cur = nums[i % n];
while (stack.length && nums[stack[stack.length - 1]] < cur) res[stack.pop()] = cur;
if (i < n) stack.push(i);
}
return res;
};