Home
DSA Patterns
Stack
Next Greater Element I
Next Greater Element I (LeetCode 496)
Next Greater Element I (LeetCode 496): find the next greater element for each value of nums1 inside nums2 with one monotonic-stack pass over nums2 and a lookup map.
Problem Understanding
Next Greater Element I: nums1 is a subset of nums2, and all values are distinct. For each value of nums1, find it in nums2 and return the first value to its right that is greater, or -1 if there is none.
Example: nums1 = [4, 1, 2], nums2 = [1, 3, 4, 2] returns [-1, 3, -1].
The Intuition: Values Waiting for Something Bigger
Walk nums2 left to right and keep a stack of values that have not yet seen anything bigger. That stack is always decreasing, which is what makes it a monotonic stack:
- When
xarrives, every smaller value on top has just met its next greater element: pop each one and recordnext[value] = x. - Push
x; it now waits. - Values still on the stack at the end have no greater element.
nums1 only needs lookups in next. The same stack solves Daily Temperatures, which records distances instead of values.
Next Greater Element I Visualization
nums1 = [4, 1, 2]
EMPTY STACK
nums2
0
1
2
3
stack (bottom → top)
EMPTY
next greater (value → next)
None yet
Walk nums2 with a stack of values still waiting for something bigger
Next
1 waits on the stack for something bigger
nums2
nums1
nums2 is on top with x filled; below it, the stack from bottom to top. Watch a big x pop several smaller values at once, each recording its next greater element in the panel beside the figure.
Next Greater Element I Dry Run
Input: nums2 = [1, 3, 4, 2]
| x | Popped | Recorded | Stack after |
|---|---|---|---|
| 1 | - | - | [1] |
| 3 | 1 | 1 → 3 | [3] |
| 4 | 3 | 3 → 4 | [4] |
| 2 | - | - | [4, 2] |
For nums1 = [4, 1, 2]: 4 and 2 were never popped, so the answer is [-1, 3, -1].
Next Greater Element I LeetCode Solution
Decreasing stack over nums2, then lookups. The C snippet uses an array as the map, since values are at most 10⁴.
Next Greater Element I Code
1var nextGreaterElement = function(nums1, nums2) {2 const nxt = new Map(), stack = [];3 for (const x of nums2) {4 while (stack.length && stack[stack.length - 1] < x) nxt.set(stack.pop(), x);5 stack.push(x);6 }7 return nums1.map((x) => nxt.get(x) ?? -1);8};
Next Greater Element I in Python, Java, C++, TypeScript and C
Next Greater Element I in Python
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
nxt, stack = {}, []
for x in nums2:
while stack and stack[-1] < x:
nxt[stack.pop()] = x
stack.append(x)
return [nxt.get(x, -1) for x in nums1]Next Greater Element I in Java
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer, Integer> nxt = new HashMap<>();
Deque<Integer> stack = new ArrayDeque<>();
for (int x : nums2) {
while (!stack.isEmpty() && stack.peek() < x) nxt.put(stack.pop(), x);
stack.push(x);
}
int[] ans = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) ans[i] = nxt.getOrDefault(nums1[i], -1);
return ans;
}
}Next Greater Element I in C++
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> nxt;
vector<int> stack;
for (int x : nums2) {
while (!stack.empty() && stack.back() < x) {
nxt[stack.back()] = x;
stack.pop_back();
}
stack.push_back(x);
}
vector<int> ans;
for (int x : nums1) ans.push_back(nxt.count(x) ? nxt[x] : -1);
return ans;
}
};Next Greater Element I in TypeScript
function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
const nxt = new Map<number, number>(), stack: number[] = [];
for (const x of nums2) {
while (stack.length && stack[stack.length - 1] < x) nxt.set(stack.pop()!, x);
stack.push(x);
}
return nums1.map((x) => nxt.get(x) ?? -1);
}Next Greater Element I in C
int* nextGreaterElement(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
int* nxt = malloc(10001 * sizeof(int));
for (int v = 0; v <= 10000; v++) nxt[v] = -1;
int* stack = malloc(nums2Size * sizeof(int));
int top = 0;
for (int i = 0; i < nums2Size; i++) {
while (top && stack[top - 1] < nums2[i]) nxt[stack[--top]] = nums2[i];
stack[top++] = nums2[i];
}
int* ans = malloc(nums1Size * sizeof(int));
for (int i = 0; i < nums1Size; i++) ans[i] = nxt[nums1[i]];
*returnSize = nums1Size;
free(nxt);
free(stack);
return ans;
}Edge Cases & Common Mistakes
- Last element of nums2: nothing is to its right, so it is never popped and its answer is -1.
- Strictly decreasing nums2: nothing is popped; every answer is -1.
- Using ≤ instead of <: values are distinct here, but in general only a strictly greater value counts.
- Searching nums2 per query: O(m · n); build the map in one pass instead.
Summary
Walk nums2 with a decreasing stack of values waiting for something bigger. Each new value pops the smaller ones and becomes their next greater element. Store the pairs in a map and answer nums1 by lookup. O(m + n) time.
More practice: DSA interview questions with answers · patterns cheat sheet
