Code Logo

Next Greater Element I

Published at23 Jul 2026
Easy 0 views
Like0

You are given two arrays nums1 and nums2 where nums1 is a subset of nums2. For each element in nums1, find its next greater element in nums2. The next greater element is the first element to the right that is strictly greater. If none exists, the answer is -1.

A monotonic decreasing stack on nums2 precomputes the next greater element for every value. As you iterate through nums2, push each element onto the stack. When the current element is greater than the top of the stack, pop and record the mapping. After processing all of nums2, use the map to look up answers for each element in nums1.

Example Input & Output

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

1 next greater: 2. 3 next greater: none. 2 next greater: 3.

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

2's NGE: 3. 4's NGE: none.

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

4's NGE: none. 1's NGE: 3. 2's NGE: none.

Algorithm Flow

Recommendation Algorithm Flow for Next Greater Element I
Recommendation Algorithm Flow for Next Greater Element I

Solution Approach

Create a hash map and an empty stack. Iterate through nums2. For each value, while the stack is not empty and the current value is greater than the top, pop and record the mapping. Push the current value. After the loop, remaining values in the stack have no next greater (map to -1). Build the result using the map for each element in nums1.

function solution(nums1, nums2) {
  var map = {}
  var stack = []
  for (var i = 0; i < nums2.length; i++) {
    var val = nums2[i]
    while (stack.length && val > stack[stack.length - 1])
      map[stack.pop()] = val
    stack.push(val)
  }
  while (stack.length) map[stack.pop()] = -1
  return nums1.map(function(x) { return map[x] })
}

Time complexity is O(n). Space complexity is O(n).

Best Answers

java
import java.util.*;
class Solution {
    public int[] solution(int[] nums1, int[] nums2) {
        Map<Integer,Integer> map = new HashMap<>();
        Stack<Integer> stack = new Stack<>();
        for (int val : nums2) {
            while (!stack.isEmpty() && val > stack.peek()) {
                int popped = stack.pop();
                if (!map.containsKey(popped)) map.put(popped, val);
            }
            stack.push(val);
        }
        while (!stack.isEmpty()) { int v = stack.pop(); if (!map.containsKey(v)) map.put(v, -1); }
        int[] result = new int[nums1.length];
        for (int i = 0; i < nums1.length; i++) result[i] = map.get(nums1[i]);
        return result;
    }
}