Maintained by Vikas Dulgunde, software engineer
You receive two arrays of distinct integers, nums1 and nums2. Every value in nums1 also occurs somewhere in nums2, so nums1 acts as a list of lookups into nums2.
For a value x, its next greater element is found by walking rightward from x inside nums2 and taking the first value you meet that exceeds x. The scan happens only in nums2, never in nums1, and it stops at the first larger value.
Build a result array the same length as nums1. The entry at position i is the next greater element for nums1[i], or -1 when no value to the right of x in nums2 is larger.
Because all values are distinct, each query has exactly one position in nums2, which keeps the lookup unambiguous.
4 sits at the end-region with only 2 after it, so -1. After 1 comes 3, which is larger, so 3. After 2 there is nothing, so -1.
The first value larger than 2 to its right is 3. Nothing follows 4, so its answer is -1.
nums1 order does not have to match nums2. After 1 in nums2 comes 2, which is larger, giving 2. Nothing to the right of 3 is larger, giving -1.
Visible test cases
The answer for each query depends only on what happens to the right of its value inside nums2, so the lookup positions in nums1 are independent of one another.
If you precompute the next greater element for every value in nums2 once, answering each nums1 query becomes a single map read.
Scan nums2 and keep a stack of values still waiting for a larger value. When the current value beats the values on top of the stack, you have just found their next greater element.
For each query value, locate it in nums2 and scan forward until a larger value appears.
Precompute the next greater element for every value in nums2 in one pass using a decreasing stack, then answer each query in constant time.