Leetcode 496. Next Greater Element I
Given two arrays nums1
and nums2
, where nums1
is a subset of nums2
, return an array representing the Next Greater Element for each element in nums1
in the order of their appearance in nums1
.
The Next Greater Element for an element x
in nums1
is the first greater element on the right of x
in nums2
. If it does not exist, output -1 for that number.
Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
Input: nums1 = [2,4], nums2 = [1,2,3,4]
Output: [3,-1]
nums1
and nums2
unique?
nums1
and nums2
?
nums1
and nums2
will not exceed 1000.nums2
from right to left. Maintain a stack that stores elements in decreasing order.nums2
:
nums1
.nums1
and use the hash map to build the result array.Here is the implementation in C++:
#include <vector>
#include <stack>
#include <unordered_map>
using namespace std;
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> ngeMap;
stack<int> s;
// Traverse nums2 from right to left
for (int i = nums2.size() - 1; i >= 0; --i) {
int num = nums2[i];
// Maintain a decreasing stack
while (!s.empty() && s.top() <= num) {
s.pop();
}
// If stack is empty, no next greater element
if (s.empty()) {
ngeMap[num] = -1;
} else {
// Top of stack is the next greater element
ngeMap[num] = s.top();
}
// Push the current num onto the stack
s.push(num);
}
// Prepare the result for nums1 based on the hashmap
vector<int> result;
for (int num : nums1) {
result.push_back(ngeMap[num]);
}
return result;
}
nums2
because each element is pushed and popped from the stack at most once.nums1
by simply looking up in the hash map.Thus, the overall time complexity is O(n + m).
nums2
. Here, n
is the length of nums2
.The suggested approach efficiently handles the problem by combining the stack data structure for next greater element calculation and hash map for quick lookups.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?