Next Greater Element

Problem

You are given two arrays (without duplicates) nums1 and nums2 where nums1's elements are subset of nums2. Find all the next greater number for nums1's elements in the corresponding places of nums2.

The Next Greater Number of a number X in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
    For number 2 in the first array, the next greater number for it in the second array is 3.
    For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

Note:

  • All elements are unique in nums1 and nums2.
  • The length of both nums1 and nums2 won't exceed 1000.

Solution

My original solution using two loops O(n^2)

public class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0) return new int[0];
        List<Integer> res = new ArrayList<>();
        outerLoop:
        for (int num1 : nums1) {
            boolean found = false;
            for (int num2 : nums2) {
                if (num1 == num2) found = true;
                else if(num2 > num1 && found) {
                    res.add(num2);
                    continue outerLoop;
                } 
            }
            res.add(-1);
        }
        return res.stream().mapToInt(i -> i).toArray();
    }
}

Optimal Solution with O(n) time

public class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<>();
        Stack<Integer> stack = new Stack<>();
        for (int num : nums2) {
            while (!stack.isEmpty() && num > stack.peek()) map.put(stack.pop(), num);
            stack.push(num);
        }
        for (int i = 0; i < nums1.length; i++) {
            nums1[i] = map.getOrDefault(nums1[i], -1);
        }
        return nums1;
    }
}

Analysis

We need to find the number from nums2 and then return the next greater element from nums2
In the first solution, we loop the smaller array and then loop the bigger array
If we find the index of number in bigger array, we set found to true
Then we add num2 if num2 > num1 && found
Notice that how we convert List<Integer> list to int[] array
We call list.stream().mapToInt(i->i).toArray()

In the optimal solution with time complexity O(n)
We use the idea that in [5, 4, 3, 2, 6] 6 is the next greater element for 5,4,3,2
Therefore we use a stack to store this kind of decreasing array
We loop through the bigger array, as long as we find its num > stack.peek()
we pop it (because the array is decreasing array) and use map to store the next greater element
At the end, we use the given smaller array and change it to required result

results matching ""

    No results matching ""