You are given two arrays nums1 and nums2 where nums1 is a subset of nums2. For each element in nums1, find its next greater element in nums2. The next greater element is the first element to the right that is strictly greater. If none exists, the answer is -1.
A monotonic decreasing stack on nums2 precomputes the next greater element for every value. As you iterate through nums2, push each element onto the stack. When the current element is greater than the top of the stack, pop and record the mapping. After processing all of nums2, use the map to look up answers for each element in nums1.
Example Input & Output
1 next greater: 2. 3 next greater: none. 2 next greater: 3.
2's NGE: 3. 4's NGE: none.
4's NGE: none. 1's NGE: 3. 2's NGE: none.
Algorithm Flow

Solution Approach
Create a hash map and an empty stack. Iterate through nums2. For each value, while the stack is not empty and the current value is greater than the top, pop and record the mapping. Push the current value. After the loop, remaining values in the stack have no next greater (map to -1). Build the result using the map for each element in nums1.
Time complexity is O(n). Space complexity is O(n).
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] nums1, int[] nums2) {
Map<Integer,Integer> map = new HashMap<>();
Stack<Integer> stack = new Stack<>();
for (int val : nums2) {
while (!stack.isEmpty() && val > stack.peek()) {
int popped = stack.pop();
if (!map.containsKey(popped)) map.put(popped, val);
}
stack.push(val);
}
while (!stack.isEmpty()) { int v = stack.pop(); if (!map.containsKey(v)) map.put(v, -1); }
int[] result = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) result[i] = map.get(nums1[i]);
return result;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
