Skip to problem
←

Next Greater Element I

Easy 0 attempts

You're given two arrays, nums1 and nums2, where every element of nums1 also appears somewhere in nums2. For each value in nums1, locate that same value's position in nums2 and find the first element to its right that is larger — this is its "next greater element." If no larger element follows it in nums2, use -1 instead.

“Next” means the first qualifying position to the right in nums2, not the smallest larger value. For query 1 in [1,5,2], the answer is 5, not 2. Do not wrap around or search to the left. Return answers in nums1 order.

Function contract

Implement nextGreaterElement(nums1, nums2). nums1 contains query values drawn from nums2; each array has distinct values.

Output: Return one value per nums1 entry, in nums1 order: the first strictly greater value to its right in nums2, or -1 if none exists.

Example 1

Input
nums1 = [4,1,2]
nums2 = [1,3,4,2]
Output
[-1,3,-1]

Example 2

Input
nums1 = [2]
nums2 = [2,1]
Output
[-1]
Constraints
  • 1 <= nums1.length <= nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 10^4
  • Values are unique within each array; every nums1 value appears in nums2

Monotonic Stack + Hash Map

Scan nums2 from left to right, keeping unresolved values in a decreasing stack. When a larger value arrives, it is the first greater value for every smaller stack top: otherwise those values would already have been removed. Record those answers in a map. Any values still unresolved at the end have no greater element to their right.

Unique values let the map use values as keys. Finally look up queries in nums1 order. Each nums2 value is pushed and popped at most once, yielding linear time.

javascript
function nextGreaterElement(nums1, nums2) {
  const map = new Map(), stack = [];
  for (const n of nums2) {
    while (stack.length && stack[stack.length-1] < n) map.set(stack.pop(), n);
    stack.push(n);
  }
  return nums1.map(n => map.get(n) ?? -1);
}

Time: O(m + n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript