496. Next Greater Element I¶
Edited by Charles
Easy · Python · Monotonic Stack
Problem
Read the original problem on LeetCode.
The official page contains the problem statement, examples, and constraints.
Explanation, examples & other approaches
Core idea
You are given two arrays nums1 and nums2, where nums1 is a subset of nums2.
For each element in nums1, find its next greater element in nums2.
Original study notes follow, including intermediate snippets and earlier attempts.
Idea¶
You are given two arrays nums1 and nums2, where nums1 is a subset of nums2.
For each element in nums1, find its next greater element in nums2.
The next greater element is the first element to the right that is strictly larger. If no such element exists, return -1.
For example:
Output:
The key observation is:
We only need to find the first greater element on the right for every element in
nums2.
This is a classic application of a monotonic stack.
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
l1, l2 = len(nums1), len(nums2)
stack = [0]
for i in range()
Monotonic Stack¶
Why Use a Stack?¶
For every element in nums2, we want to know the first greater element to its right.
A brute-force solution scans to the right for every element, resulting in O(n²) time complexity.
Instead, we maintain a monotonic stack so that each element is pushed and popped at most once, reducing the complexity to O(n) for processing nums2.
What Should Be Stored in the Stack?¶
The stack stores indices of elements in nums2.
Whenever the value is needed, simply access
What Kind of Monotonic Stack?¶
Since we are searching for the next greater element, we maintain a monotonically decreasing stack.
That means:
For example,
Whenever a larger value appears, it becomes the next greater element for all smaller values on the top of the stack.
State Transition¶
During traversal of nums2, there are three situations.
Case 1: Current value is smaller¶
If
the current value cannot be the next greater element for any previous number.
Push its index into the stack.
Case 2: Current value is equal¶
If
push it into the stack as well.
The problem asks for the next strictly greater element, so equal values cannot resolve previous elements.
Case 3: Current value is greater¶
If
then the current value is the next greater element for the stack top.
Continue popping while the current value is larger.
For every popped index:
- Check whether the corresponding value exists in
nums1. - If it does, update the answer.
After all smaller elements are processed,
push the current index.
Example¶
Initialization:
i = 1 (value = 2)¶
Pop index 0.
Since 1 is not in nums1, ignore it.
Push index 1.
i = 2 (value = 3)¶
Pop index 1.
Since 2 is in nums1:
Push index 2.
i = 3 (value = 4)¶
Pop index 2.
3 is not in nums1.
Push index 3.
Traversal finishes.
The remaining element (4) has no greater element on its right, so its answer remains -1.
Final result:
Complexity Analysis¶
Current Implementation¶
Time Complexity
where
n = len(nums2)m = len(nums1)
Although the monotonic stack itself is O(n), the following operations are both linear:
Each pop may perform an O(m) search.
Space Complexity
The stack may contain all indices.
Optimization¶
A better approach is to build a hash map:
For example:
Then both lookup operations become O(1):
Overall complexity becomes:
Summary¶
Data Structure
Stack Content
Monotonic Property
Transition
Traversal Order
Final Answer
Common Mistakes¶
- Store indices, not values.
- The comparison should be:
because we need the next strictly greater element.
- Continue popping while the current value is larger.
- The remaining elements in the stack have no greater element on the right, so their answers remain -1
- Performance Improvement
The current implementation uses:
Both operations are O(m).
Replacing them with a hash map reduces the overall complexity from O(n × m) to O(n).
Study record
| Field | Value |
|---|---|
| Attempts | 1 |
| Mastery | ❚ |
| The Latest Attempt | August 13, 2026 |
Python solution¶
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
l1 = len(nums1)
l2 = len(nums2)
res = [-1] * l1
stack = [0]
for i in range(1, l2):
if nums2[i] <= nums2[stack[-1]]:
stack.append(i)
else:
while len(stack) != 0 and nums2[i] > nums2[stack[-1]]:
if nums2[stack[-1]] in nums1:
idx = nums1.index(nums2[stack[-1]])
res[idx] = nums2[i]
stack.pop()
stack.append(i)
return res