496. Next Greater Element I
Asked at 14Bloomberg60Amazon56Microsoft49Google45Meta43Apple30Flipkart64Swiggy82Barclays53Agoda48Accenture44tcs36TikTok26Uber22
Problem
nums1 is a subset of nums2 (all values distinct). For each value x of nums1, find x in nums2 and return the first greater value to its right, or −1 if there is none.
Example: nums1 = [4,1,2], nums2 = [1,3,4,2] → [-1,3,-1]
Constraints: follow-up: O(len(nums1) + len(nums2)).
Compute next-greater for every value of nums2 with a decreasing stack and store it in a map; answer queries from nums1.
Complexity: O(n + m).
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
nxt, st = {}, []
for x in nums2:
while st and st[-1] < x:
nxt[st.pop()] = x
st.append(x)
return [nxt.get(x, -1) for x in nums1]
assert Solution().nextGreaterElement([4, 1, 2], [1, 3, 4, 2]) == [-1, 3, -1]
assert Solution().nextGreaterElement([2, 4], [1, 2, 3, 4]) == [3, -1]
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer, Integer> nxt = new HashMap<>();
Deque<Integer> st = new ArrayDeque<>();
for (int x : nums2) {
while (!st.isEmpty() && st.peek() < x) nxt.put(st.pop(), x);
st.push(x);
}
int[] res = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) res[i] = nxt.getOrDefault(nums1[i], -1);
return res;
}
}
func nextGreaterElement(nums1 []int, nums2 []int) []int {
nxt, st := map[int]int{}, []int{}
for _, x := range nums2 {
for len(st) > 0 && st[len(st)-1] < x {
nxt[st[len(st)-1]] = x
st = st[:len(st)-1]
}
st = append(st, x)
}
res := make([]int, len(nums1))
for i, x := range nums1 {
if v, ok := nxt[x]; ok {
res[i] = v
} else {
res[i] = -1
}
}
return res
}