Next Greater Element II
Next Greater Element II is a medium monotonic stack problem solved with the monotonic stack pattern.
The best approach, optimal (monotonic stack over two passes), runs in O(n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force up.
Problem
Given a circular array, return the next greater number for every element: the first larger value found by moving right and wrapping around the end. If none exists, use -1.
Examples
Example 1
- Input
nums = [3, 8, 4, 1]- Output
[8, -1, 8, 3]- Why
- The array is circular: after 1 comes 3, then 8.
Example 2
- Input
nums = [5, 5]- Output
[-1, -1]
Constraints
1 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force | O(n²) | O(1) |
| Optimal (monotonic stack over two passes) | O(n) | O(n) |
1Brute force
O(n²)O(1)For each index, check the next n - 1 elements circularly.
- For each i, for k = 1..n-1, look at nums[(i + k) % n].
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] out = new int[n];
for (int i = 0; i < n; i++) {
out[i] = -1;
for (int k = 1; k < n; k++)
if (nums[(i + k) % n] > nums[i]) { out[i] = nums[(i + k) % n]; break; }
}
return out;
}
}class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
n = len(nums)
out = [0] * n
for i in range(n):
out[i] = -1
for k in range(1, n):
if nums[(i + k) % n] > nums[i]:
out[i] = nums[(i + k) % n]
break
return outclass Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = nums.size();
vector<int> out(n);
for (int i = 0; i < n; i++) {
out[i] = -1;
for (int k = 1; k < n; k++)
if (nums[(i + k) % n] > nums[i]) { out[i] = nums[(i + k) % n]; break; }
}
return out;
}
};function nextGreaterElements(nums) {
const n = nums.length;
const out = new Array(n);
for (let i = 0; i < n; i++) {
out[i] = -1;
for (let k = 1; k < n; k++)
if (nums[(i + k) % n] > nums[i]) { out[i] = nums[(i + k) % n]; break; }
}
return out;
}2Optimal (monotonic stack over two passes)
O(n)O(n)Run the usual next-greater stack for i from 0 to 2n - 1 with index i % n. Only push during the first pass; the second pass exists to resolve elements whose answer lies before them.
- Fill out with -1.
- For i in 0..2n-1: while stack top value < nums[i % n], out[pop()] = nums[i % n].
- If i < n, push i.
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<>();
for (int i = 0; i < 2 * n; i++) {
int x = nums[i % n];
while (!st.isEmpty() && nums[st.peek()] < x) out[st.pop()] = x;
if (i < n) st.push(i);
}
return out;
}
}class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
n = len(nums)
out = [-1] * n
st = []
for i in range(2 * n):
x = nums[i % n]
while st and nums[st[-1]] < x:
out[st.pop()] = x
if i < n:
st.append(i)
return outclass Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = nums.size();
vector<int> out(n, -1);
vector<int> st;
for (int i = 0; i < 2 * n; i++) {
int x = nums[i % n];
while (!st.empty() && nums[st.back()] < x) { out[st.back()] = x; st.pop_back(); }
if (i < n) st.push_back(i);
}
return out;
}
};function nextGreaterElements(nums) {
const n = nums.length;
const out = new Array(n).fill(-1);
const st = [];
for (let i = 0; i < 2 * n; i++) {
const x = nums[i % n];
while (st.length > 0 && nums[st[st.length - 1]] < x) out[st.pop()] = x;
if (i < n) st.push(i);
}
return out;
}Edge cases to test
- The maximum element (always -1)
- All equal values
Hints
Hint 1
Walk the array twice (indices 0 .. 2n - 1, using i % n) so every element can see around the end.
FAQ
What is the best time complexity for Next Greater Element II?
Optimal (monotonic stack over two passes) runs in O(n) time and O(n) extra space.
Which pattern does Next Greater Element II use?
It is a monotonic stack problem that uses the monotonic stack pattern. Other problems with the same pattern: Next Greater Element I, Daily Temperatures, Largest Rectangle in Histogram.
Is there a brute force solution for Next Greater Element II?
Yes. Brute force takes O(n²) time and O(1) space. For each index, check the next n - 1 elements circularly.
Which edge cases should I test for Next Greater Element II?
The maximum element (always -1); All equal values.