Time: → Reason: Iterating through each input array once
Space: → Reason: Hashmap equal to length of nums1
Code
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
stack = []
result = [-1] * len(nums1)
hashmap = {}
for i, num in enumerate(nums1):
hashmap[num] = i
for num in nums2:
while stack and num > stack[-1]:
foundNextGreaterFor = stack.pop()
# we found the next greater item for foundNextGreaterFor value
result[hashmap[foundNextGreaterFor]] = num
if num in hashmap:
stack.append(num)
return result
Common Mistakes / Things I Got Stuck On
Trying to use Increasing Monotonic Stack instead of decreasing