## Next Greater Element

### 496. Next Greater Element I

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Thought Process:

• Iterate over the numbers in nums2, create a hashmap annotating the next greater element for each number.
• This annotation is done via a stack, before we push a number onto the stack, we check the top element on the stack. If the top element is smaller than the push element, we insert this key value pair to the hashmap and pop the top.
• Once the top element is greater or equal to the push element or the stack becomes empty, we can resume the push.
def nextGreaterElement(nums1, nums2):
mapping = defaultdict(lambda: -1)
stack = []
for num in nums2:
while stack and stack[-1] < num: mapping[stack.pop()] = num
stack.append(num)

return [mapping[num] for num in nums1]


### 503. Next Greater Element II

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn’t exist, output -1 for this number.

Thought Process:

• Since the array is circular, we have to scan at least twice to make sure we find each number the next greater number.
def nextGreaterElements(nums):
next_greater = [-1] * len(nums)
stack = []
for i, num in chain(enumerate(nums), enumerate(nums)):
while stack and nums[stack[-1]] < num: next_greater[stack.pop()] = num
stack.append(i)
return next_greater