Next Greater Element I — Monotonic Stack with HashMap
Advertisement
Problem 262 · Next Greater Element I
Difficulty: Medium · Pattern: Monotonic Stack + HashMap
For each element in nums1, find the first greater element to its right in nums2.
Solutions
# Python
def nextGreaterElement(nums1, nums2):
nge = {} # val -> next greater in nums2
stack = []
for x in nums2:
while stack and stack[-1] < x:
nge[stack.pop()] = x
stack.append(x)
return [nge.get(x, -1) for x in nums1]
// Java
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer,Integer> nge = new HashMap<>();
Deque<Integer> stack = new ArrayDeque<>();
for (int x : nums2) {
while (!stack.isEmpty() && stack.peek() < x) nge.put(stack.pop(), x);
stack.push(x);
}
int[] res = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) res[i] = nge.getOrDefault(nums1[i], -1);
return res;
}
Complexity
- Time: O(n + m)
- Space: O(n)
Advertisement