Problem Description
Given two distinct 0-indexed integer arrays, nums1 (a subset of nums2) and nums2, for each element in nums1, find the first greater element to its right in nums2. If it does not exist, return -1 for that element.
Key Insights
- Use a monotonic decreasing stack to precompute the next greater element for every number in nums2.
- Use a hash map to store the mapping from element to its next greater element.
- For each element in nums1, look up the next greater element from the hash map.
- This approach avoids a nested loop by processing nums2 only once.
Space and Time Complexity
Time Complexity: O(n) where n is the length of nums2 (plus O(m) for nums1, overall O(n + m)). Space Complexity: O(n) for the stack and hash map.
Solution
We iterate through nums2 once while maintaining a stack that keeps numbers in decreasing order. When a new number is encountered, it is the next greater element for all numbers in the stack that are smaller than it. These elements are popped from the stack and the mapping is recorded in a hash map. Afterwards, for each element in nums1, we simply fetch the answer from the hash map. This ensures an optimal O(n + m) solution.