The next greater element of some element x in array nums2 is the first element to the right of x in nums2 that is strictly greater. Given nums1 (a subset of nums2), for each element in nums1, find its next greater element in nums2. Return -1 if it does not exist.
nums1 = [4,1,2], nums2 = [1,3,4,2][-1,3,-1]nums1 = [2,4], nums2 = [1,2,3,4][3,-1]map and stackn in nums2: while stack top < n, pop and record map[top] = nn onto the stack (stack stays decreasing)-1nums1: look up in map, default -1
We keep the stack in decreasing order. When a new element n is encountered and it is larger than the top, that top element has finally found its next greater element. We pop and record it. Elements that never get popped have no next greater element (they remain -1). The HashMap then gives O(1) lookup for any query in nums1.