Next Greater Element II
Pattern: Monotonic stack
The array is circular, so walk it twice (index i mod n) with a stack of indexes still waiting. A new value answers every smaller waiter. Only the first lap pushes indexes; the second lap only answers them.
The problem
Given a circular array, return for each value the first greater value met going right and wrapping round, or -1.
[1, 2, 1] gives [2, -1, 2]; [1, 2, 3, 4, 3] gives [2, 3, 4, -1, 4].
Think first
- How does circular change the search?
- How far right can the answer be?
- How do you simulate the wrap without copying the array?
Hints
Brute force, and why it fails
For each index, step right up to n - 1 times with wrap-around: O(n²).
The key insight
Two laps show every index all the values that could answer it, and the monotonic stack answers each index once.
Dry run
10
21
12
| stack | 1 2 |
|---|---|
| out | [2, -1, -1] |
nums = [1, 2, 1]. Lap 1: push 0; 2 answers index 0 (out[0] = 2), push 1; push 2.
Step 1 of 3
The plan
out = [-1] * n; stack = []
for k from 0 to 2n - 1:
i = k mod n
while stack and nums[top] < nums[i]: out[pop] = nums[i]
if k < n: push i
Complexity
- Time
O(n)- Space
O(n)
2n steps; each index is pushed once and popped at most once.
Edge cases
- All equal: all
-1. - One value:
-1. - Strictly decreasing: all answers come from the wrap except the first value's.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] out = new int[n];
Arrays.fill(out, -1);
Deque<Integer> st = new ArrayDeque<>(); // indexes still waiting for a greater value
for (int k = 0; k < 2 * n; k++) { // two laps cover the wrap-around
int i = k % n;
while (!st.isEmpty() && nums[st.peek()] < nums[i]) out[st.pop()] = nums[i];
if (k < n) st.push(i); // only the first lap adds waiters
}
return out;
}
}C++
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = static_cast<int>(nums.size());
vector<int> out(n, -1);
stack<int> st; // indexes still waiting for a greater value
for (int k = 0; k < 2 * n; k++) { // two laps cover the wrap-around
int i = k % n;
while (!st.empty() && nums[st.top()] < nums[i]) { out[st.top()] = nums[i]; st.pop(); }
if (k < n) st.push(i); // only the first lap adds waiters
}
return out;
}
};Python
class Solution:
def nextGreaterElements(self, nums: list[int]) -> list[int]:
n = len(nums)
out, st = [-1] * n, [] # st: indexes still waiting for a greater value
for k in range(2 * n): # two laps cover the wrap-around
i = k % n
while st and nums[st[-1]] < nums[i]:
out[st.pop()] = nums[i]
if k < n:
st.append(i) # only the first lap adds waiters
return outCommon mistakes
- Pushing in the second lap, which can give an index the wrong answer later.
- Storing values instead of indexes, so you cannot write the answer.