Next Greater Element I Easy 0 attempts
LeetCode ↗

Next Greater Element I

Easy Stack&Queue LeetCode

Given two arrays nums1 (subset of nums2), for each element in nums1 find the next greater element in nums2. Return -1 if no greater element exists.

Example: nums1 = [4,1,2], nums2 = [1,3,4,2] → Output: [-1,3,-1]

Sample Input
Sample Output
Constraints
  • 1 <= nums1.length <= nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 10^4
  • All values in nums1 and nums2 are unique
Test Cases
Case 1
Args: [[4,1,2],[1,3,4,2]] Expected: [-1,3,-1]
Topics

Monotonic Stack + Hash Map

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)

Saved in this browser only. Private to you.

JavaScript