LeetCode 496 Next Greater Element I - Solution

The core idea

Build a map of next greater elements for all numbers in nums2, then look up answers for nums1.

Use a monotonic decreasing stack. Iterate through nums2:

  • While the stack isn't empty and current element is greater than stack top, pop the top. The current element is the "next greater" for that popped element. Store it in a hash map.
  • Push current element onto the stack.

Elements remaining on the stack have no next greater element.

For each element in nums1, look up its answer in the map.