• Time:O(n)
• Space:O(n)

## C++

``````class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
vector<int> ans;
unordered_map<int, int> numToNextGreater;
stack<int> stack;  // decreasing stack

for (const int num : nums2) {
while (!stack.empty() && stack.top() < num)
numToNextGreater[stack.top()] = num, stack.pop();
stack.push(num);
}

for (const int num : nums1)
if (numToNextGreater.count(num))
ans.push_back(numToNextGreater[num]);
else
ans.push_back(-1);

return ans;
}
};
``````

## JAVA

``````class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
List<Integer> ans = new ArrayList<>();
Map<Integer, Integer> numToNextGreater = new HashMap<>();
Deque<Integer> stack = new ArrayDeque<>(); // decreasing stack

for (final int num : nums2) {
while (!stack.isEmpty() && stack.peek() < num)
numToNextGreater.put(stack.pop(), num);
stack.push(num);
}

for (final int num : nums1)
if (numToNextGreater.containsKey(num))
else

return ans.stream().mapToInt(i -> i).toArray();
}
}
``````

## Python

``````class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
numToNextGreater = {}
stack = []

for num in nums2:
while stack and stack[-1] < num:
numToNextGreater[stack.pop()] = num
stack.append(num)

return [numToNextGreater.get(num, -1) for num in nums1]
``````