Algo-Sim › Stacks & Monotonic Stack
Next Greater Element
Easy · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input
For every element, find the first element to its right that is strictly greater, or -1 if there is none.
Problem
For each element of nums, find the first element to its right that is strictly larger. Return these values in an array, using -1 where no larger element follows.
Constraints
- 1 ≤ nums.length ≤ 10⁵
- -10⁹ ≤ nums[i] ≤ 10⁹
- Scanning right from every element is O(n²); aim for O(n)
Edge cases to test
- Strictly decreasing: all
-1 - Equal values (strictly greater only)
- One element
Follow-up questions
- What if the array is circular?
- Loop over 2n indices with
i % n, pushing only in the first pass (LC 503): O(n). - How do you answer it for a subset of the values?
- Run the stack once over the full array and store answers in a map from value to next greater (LC 496).
Solution
Java
public int[] nextGreaterElement(int[] nums) {
int n = nums.length;
int[] result = new int[n];
Arrays.fill(result, -1);
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
int idx = stack.pop();
result[idx] = nums[i];
}
stack.push(i);
}
return result;
}Python
def next_greater_element(nums):
n = len(nums)
result = [-1] * n
stack = []
for i in range(n):
while stack and nums[stack[-1]] < nums[i]:
idx = stack.pop()
result[idx] = nums[i]
stack.append(i)
return resultC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> nextGreaterElement(vector<int> &nums) {
int n = int(nums.size());
vector<int> result = vector<int>(n);
fill(result.begin(), result.end(), -1);
deque<int> stack = {};
for (int i = 0; i < n; i++) {
while (!stack.empty() && nums[stack.back()] < nums[i]) {
int idx = stack.back();
stack.pop_back();
result[idx] = nums[i];
}
stack.push_back(i);
}
return result;
}
};
More Stacks & Monotonic Stack problems
- Valid Parentheses (Easy)
- Implement Queue using Stacks (Easy)
- Evaluate Reverse Polish Notation (Medium)
- Basic Calculator II (Medium)
- Basic Calculator (Hard)
- Decode String (Medium)
- Asteroid Collision (Medium)
- Daily Temperatures (Medium)
- Remove K Digits (Medium)
- Online Stock Span (Medium)
- Car Fleet (Medium)
- Largest Rectangle in Histogram (Hard)
- Maximal Rectangle (Hard)
- Sliding Window Maximum (Hard)