Next Greater Element I
LeetCode 496 · Easy · solution, intuition & step-by-step walkthrough
Monotonic decreasing stack over nums2 + hash map.
This is how I solved Next Greater Element I (LeetCode 496), an easy problem from the Monotonic Stack – Next / Previous Greater or Smaller pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Find the next greater element for every number in nums2 once, using a monotonic stack: a number waits on the stack until a bigger number arrives and resolves it. Then answer nums1 with lookups.
Approach
- 1
Scan nums2; while the current value beats the stack top, pop it and record the answer.
- 2
Push the current index.
- 3
For each value in nums1, read the map (default −1).
How I solved it
Monotonic stack + mapPythonO(n+m) time
class Solution:
def nextGreaterElement(self, nums1: list[int], nums2: list[int]) -> list[int]:
"""
[4,1,2]
[1,3,4,2]
[-1,3,-1]
monotonic stack - monotoncally increasing stack
"""
stack = []
n = len(nums2)
hash_map = {}
i=0
while i<n:
while stack and nums2[i]>nums2[stack[-1]]:
index = stack.pop()
hash_map[nums2[index]]=nums2[i]
stack.append(i)
i+=1
res = []
for num in nums1:
if num in hash_map:
res.append(hash_map[num])
else:
res.append(-1)
return res
Next Greater Element I — FAQ
What is the intuition behind Next Greater Element I?
Find the next greater element for every number in nums2 once, using a monotonic stack: a number waits on the stack until a bigger number arrives and resolves it. Then answer nums1 with lookups.
How do you solve Next Greater Element I (LeetCode 496)?
1. Scan nums2; while the current value beats the stack top, pop it and record the answer. 2. Push the current index. 3. For each value in nums1, read the map (default −1).
What is the time and space complexity of Next Greater Element I?
Time: O(n + m). Space: O(n). (Accepted approach: Monotonic stack + map.)
What are common mistakes in Next Greater Element I?
Values are unique, so mapping by value is safe.