LeetCode 496: Next Greater Element I

link

It’s a mapping problem: nums1 -> nums2 -> next_greater_element. To build the mapping nums2 -> next_greater_element, we take the approach in the next warmer day problem.

Time: \mathcal{O}(|\texttt{nums2}|), space: \mathcal{O}(|\texttt{nums2}|).

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        next_greater = {}
        stack = []
        for x in nums2:
            while stack and x > (top := stack[-1]):
                next_greater[top] = x
                stack.pop()
            stack.append(x)
        # Throw away numbers without a next greater element
        stack = None

        ans = []
        for x in nums1:
            ans.append( next_greater.get(x, -1) )
        return ans

Leave a comment