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 INPUT nums1 (subset) 4 1 2 nums2 (main array) 1 3 4 2 i=0 i=1 i=2 i=3 Find next greater element for each nums1 value in nums2 array Next Greater Mapping: 1 --> 3 (right of 1) 4 --> -1 (none) 2 --> -1 (none) ALGORITHM STEPS 1 Build Hash Map Store next greater for each element in nums2 2 Use Stack Traverse nums2, maintain decreasing stack 3 Pop and Map When current > stack top, map[pop] = current 4 Query nums1 For each nums1[i], lookup in hash map Hash Map Built: 1: 3 3: 4 4: -1 2: -1 FINAL RESULT Query Process: nums1[0] = 4 map[4] = -1 nums1[1] = 1 map[1] = 3 nums1[2] = 2 map[2] = -1 Output Array: -1 3 -1 i=0 i=1 i=2 OK - Answer: [-1,3,-1] Key Insight: Use a monotonic decreasing stack to find next greater elements in O(n) time. When we see a larger element, pop smaller elements from stack and map them to the current element. Store results in a hash map for O(1) lookup when querying nums1 elements. TutorialsPoint - Next Greater Element I | Hash + Stack Approach
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