Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Stacks
Amazon
Next Greater Element I

For each element in a subset array, find the first greater value that appears to its right in a larger array.

Acceptance 0%
Problem Statement

Problem

You are given two integer arrays, nums1 and nums2, where every value in nums1 appears in nums2 and both arrays contain distinct values.

For each element x in nums1, find the next greater element of x in nums2 — the first number strictly larger than x that appears to the right of x in nums2.

Return an array ans such that ans[i] is the next greater element of nums1[i]. If no greater element exists to the right, use -1.

Notes

  • The next greater element is searched only in nums2.
  • Each query in nums1 should be answered based on its position in nums2.
  • Values are distinct, so each number can be matched unambiguously.

Input Format

  • Two integer arrays nums1 and nums2
  • nums1 is a subset of nums2
  • All values are distinct

Output Format

  • Return an integer array ans
  • ans[i] is the next greater element of nums1[i] in nums2, or -1 if none exists

Constraints

  • 1 <= nums1.length <= nums2.length
  • 1 <= nums2.length
  • Elements are distinct
  • Every element of nums1 appears in nums2
Examples
Sample cases returned by the problem API.

Example 1

Input

nums1 = [4,1,2]
nums2 = [1,3,4,2]

Output

[-1,3,-1]

Explanation

  • For 4, there is no greater number to its right in nums2.
  • For 1, the next greater number to its right is 3.
  • For 2, there is no greater number to its right.

Example 2

Input

nums1 = [2,4]
nums2 = [1,2,3,4]

Output

[3,-1]

Explanation

  • For 2, the first greater value to its right is 3.
  • For 4, nothing greater appears after it, so the answer is -1.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.