Next Greater Element
Try to solve the Next Greater Element problem.
We'll cover the following
Statement#
Given the two distinct integer arrays, nums1 and nums2, where nums1 is a subset of nums2, find all the next greater elements for nums1 values in the corresponding places of nums2.
In general, the next greater element of an element, , in an array is the first greater element present on the right side of in the same array. However, in the context of this problem, for each element in nums1, find the next greater element present on the right side of in nums2 and store it in the ans array. If there is no such element, store for this number. The ans array should be of the same length as nums1, and the order of the elements in the ans array should correspond to the order of the elements in nums1.
Return the ans array after finding the next greater elements.
Note: The input data may or may not be sorted.
Constraints:
-
nums1.lengthnums2.length -
nums1[i],nums2[i] nums1have distinct integers.nums2have distinct integers.- All integers in
nums1also appear innums2.
Examples#
1 of 2
2 of 2
Understand the problem#
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Next Greater Element
What is the output if the following arrays are given as input?
nums1 = [5, 4, 7]
nums2 = [4, 5, 7, 3]
ans = [7, 7, 3]
ans = [7, 7, -1]
ans = [7, 5, -1]
ans = [7, 5, 3]
Figure it out!#
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself#
Implement your solution in the following coding playground.
Solution: Logger Rate Limiter
Solution: Next Greater Element