We use a monotonic stack to precompute all next greater elements in nums2. We store these results in a hash map. Then, we simply query the map for each element in nums1.
- Initialize an empty stack and a dictionary
mapping. - Iterate through each
numinnums2:- While stack is not empty and
num> top of stack:temp = stack.pop()mapping[temp] = num
- Push
numto stack.
- While stack is not empty and
- For values remaining in stack, set their
mappingvalue to -1. - Build the result for
nums1using themapping.
- Time Complexity: O(N + M), where N, M are lengths of
nums1andnums2. Each element innums2is pushed and popped exactly once. - Space Complexity: O(M) for map and stack.
def next_greater_element(nums1, nums2):
mapping = {}
stack = []
for num in nums2:
while stack and num > stack[-1]:
mapping[stack.pop()] = num
stack.append(num)
while stack:
mapping[stack.pop()] = -1
return [mapping[num] for num in nums1]