...

/

Next Greater Element

Next Greater Element

Try to solve the Next Greater Element I problem.

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, xx, in an array is the first greater element present on the right side of xx in the same array. However, in the context of this problem, for each element xx in nums1, find the next greater element present on the right side of xx in nums2 and store it in the ans array. If there is no such element, store 1-1 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:

  • 11 \leq nums1.length \leq nums2.length 103\leq 10^3
  • 00 \leq nums1[i], nums2[i] 104\leq 10^4
  • nums1 have distinct integers.
  • nums2 have distinct integers.
  • All integers in nums1 also appear in nums2.

Examples

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

1.

What is the output if the following arrays are given as input?

nums1 = [5, 4, 7]

nums2 = [4, 5, 7, 3]

A.

ans = [7, 7, 3]

B.

ans = [7, 7, -1]

C.

ans = [7, 5, -1]

D.

ans = [7, 5, 3]


1 / 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.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

JavaScript
usercode > main.js
function nextGreaterElement(nums1, nums2){
// Replace this placeholder return statement with your code
return [];
}
export {
nextGreaterElement
}
Next Greater Element I

Access this course and 1200+ top-rated courses and projects.