Next Greater Element I - Problem

The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.

You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.

For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.

Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
💡 Note: For 4: appears at index 2 in nums2, no greater element to the right → -1. For 1: appears at index 0, next greater is 3 → 3. For 2: appears at index 3, no greater element to the right → -1.
Example 2 — All Elements Found
$ Input: nums1 = [2,4], nums2 = [1,2,3,4]
Output: [3,-1]
💡 Note: For 2: appears at index 1 in nums2, next greater is 3 → 3. For 4: appears at index 3, no greater element to the right → -1.
Example 3 — Single Element
$ Input: nums1 = [1], nums2 = [1,2]
Output: [2]
💡 Note: For 1: appears at index 0 in nums2, next greater is 2 → 2.

Constraints

  • 1 ≤ nums1.length ≤ nums2.length ≤ 1000
  • 0 ≤ nums1[i], nums2[i] ≤ 104
  • All integers in nums1 and nums2 are unique
  • All the integers of nums1 also appear in nums2

Visualization

Tap to expand
Next Greater Element I: Problem Overviewnums1 (queries):412nums2 (search space):13424 → no next greater → -11 → next greater is 3 → 32 → no next greater → -1Result: [-1, 3, -1]
Understanding the Visualization
1
Input
nums1 = [4,1,2] (queries), nums2 = [1,3,4,2] (search space)
2
Process
For each element in nums1, find its next greater element in nums2
3
Output
Return array with next greater elements or -1 if none exist
Key Takeaway
🎯 Key Insight: Use a monotonic stack to precompute next greater elements, then lookup queries in O(1) time
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
180.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen