SDE & MLE Prep

496. Next Greater Element I

Problem

nums1 is a subset of nums2 (all values distinct). For each value x of nums1, find x in nums2 and return the first greater value to its right, or −1 if there is none.

Example: nums1 = [4,1,2], nums2 = [1,3,4,2] → [-1,3,-1]

Constraints: follow-up: O(len(nums1) + len(nums2)).

Compute next-greater for every value of nums2 with a decreasing stack and store it in a map; answer queries from nums1.

Complexity: O(n + m).

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nxt, st = {}, []
        for x in nums2:
            while st and st[-1] < x:
                nxt[st.pop()] = x
            st.append(x)
        return [nxt.get(x, -1) for x in nums1]