Next Greater Element

For each number of one array, find the first bigger number to its right in a second array.

In an array, the next greater element of a number is the first number to its right that is bigger than it. You are given two arrays, nums1 and nums2, and no number appears twice in either of them. Every number of nums1 also appears in nums2. For each number of nums1, return its next greater element in nums2, or -1 if no bigger number comes after it there. The answers come in the order of nums1.

Example 1
Input: nums1 = [4, 1, 2], nums2 = [1, 3, 4, 2]
Output: [-1, 3, -1]
Explanation: in nums2, nothing after 4 is bigger; after 1, the first bigger number is 3; nothing after 2 is bigger.
Example 2
Input: nums1 = [3, 7, 1], nums2 = [6, 3, 1, 4, 2, 7]
Output: [4, -1, 4]
Solution

The Idea

Picture six people standing in a row, each holding a card with a number: 6, 3, 1, 4, 2 and 7, the nums2 of Example 2. Each person looks to the right for the first card with a bigger number. The person holding 3 sees 1 first, which is smaller, and then 4, which is bigger, so the answer for 3 is 4. The person holding 7 stands at the end of the row, with nobody to the right, so the answer for 7 is -1.

nums1 = [3, 7, 1] only says which of the six answers to report: 4 for 3, -1 for 7, and 4 for 1. The real work is finding the answers in nums2.

The direct way does what the people do: for each number, walk right until a bigger one turns up. For 6, that walk passes 3, 1, 4 and 2 before it reaches 7. The walk for 3 then passes 1 and 4 again, and on a longer array the same numbers get looked at over and over. Could a single pass from left to right answer everyone instead?

Try it. Read nums2 from left to right, and keep a list of the numbers still waiting for their answer. Look at the picture below. Each row shows the number just read, the numbers waiting after it, and the answers it gave.

Reading 6, 3, 1, 4, 2, 7 from left to right. Each number joins the waiting numbers. Reading 4 answers 1 and 3, and 6 keeps waiting. Reading 7 answers 2, 4 and 6. 7 is still waiting at the end, so its answer is -1.

In the first three rows, 6, 3 and 1 join the waiting numbers. Each is smaller than the one before, so none of them answers anyone. In the fourth row, 4 arrives. It is bigger than 1 and 3, and it is the first bigger number after them, because a bigger number in between would have answered them already. So 4 answers both. 6 is bigger than 4 and keeps waiting, and 4 joins the list. In the last row, 7 answers 2, 4 and 6 at once.

Now look at the waiting numbers in every row: they always go down from oldest to newest, like 6, 3, 1 or 6, 4, 2. A new number first removes every smaller number at the newest end, and only then joins. So a new number compares itself with the newest waiting numbers only, and it can stop at the first one that is bigger, because all the older ones are bigger still.

A list that only changes at one end, where the last number added is the first one taken off, is called a stack. Here the numbers in the stack always go down, in one direction, so it is called a monotonic stack (monotonic means always moving the same way).

Solution Approach

Turning that idea into code means settling three things: why to answer every number of nums2, how to keep the waiting numbers, and how to hand the answers back in the order of nums1.

Answering every number of nums2

Why answer all of nums2, when nums1 asks about only some of its numbers? The direct way finds each number of nums1 in nums2 and walks right from there. With m numbers in nums1 and n in nums2, each search and walk can take up to n steps, so the whole job takes up to about m × n steps. One pass over nums2 answers every number, and then each number of nums1 only needs to look its answer up.

Keeping the waiting numbers

Which Java type holds the stack? It needs three operations: look at the newest number, take it off, and add a new one. ArrayDeque, a class in java.util that stores items in a growing array and can add and remove them at both ends, offers these as peek, pop and push. Java also has an older Stack class, but its own documentation recommends the Deque interface, which ArrayDeque implements, instead.

Is one pass really fast, when a single new number may answer many waiting ones, as 7 did? Each number is added to the stack once and taken off at most once. So the whole pass has at most n removals, however they are spread over the rows. Each read also ends with at most one comparison that removes nothing, which adds at most n more steps.

Handing the answers back

Where do the answers go until nums1 asks for them? Each time a number is taken off the stack, its answer goes into a HashMap, a table that finds a value by its key in one step on average. Here the key is the number and the value is its next greater element. This works because no number appears twice in nums2, so each number has exactly one answer.

Numbers still on the stack at the end never got an answer, so they are not in the map. getOrDefault(key, -1) returns -1 for a key that is missing, which is exactly the answer they need.

Java Solution

The method nextGreaterElement works in these steps:

  1. First, create the map nextGreater for the answers and an ArrayDeque called stack for the waiting numbers.
  2. Read nums2 from left to right with a loop, one number x at a time. Inside, a while loop takes numbers off stack as long as the newest one, stack.peek(), is smaller than x, and stores x in nextGreater as the answer of each one.
  3. Then push x onto stack, where it waits for its own answer.
  4. After the loop, create the array result, as long as nums1. A second loop fills it: for each nums1[i], nextGreater.getOrDefault(nums1[i], -1) gives its answer, or -1 if it never got one.
  5. Return result.

The main method runs both examples, then a nums2 whose numbers only go up and one whose numbers only go down.

Java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;

public class NextGreaterElement1 {

    public static int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map<Integer, Integer> nextGreater = new HashMap<>();   // value -> its next greater value
        Deque<Integer> stack = new ArrayDeque<>();             // values still waiting
        for (int x : nums2) {
            while (!stack.isEmpty() && stack.peek() < x) {
                nextGreater.put(stack.pop(), x);   // x is the first bigger value to its right
            }
            stack.push(x);
        }
        int[] result = new int[nums1.length];
        for (int i = 0; i < nums1.length; i++) {
            result[i] = nextGreater.getOrDefault(nums1[i], -1);   // never answered: -1
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(
                nextGreaterElement(new int[] {4, 1, 2}, new int[] {1, 3, 4, 2})));
        System.out.println(Arrays.toString(
                nextGreaterElement(new int[] {3, 7, 1}, new int[] {6, 3, 1, 4, 2, 7})));
        System.out.println(Arrays.toString(
                nextGreaterElement(new int[] {1, 2, 3, 4}, new int[] {1, 2, 3, 4})));
        System.out.println(Arrays.toString(
                nextGreaterElement(new int[] {5, 4, 3}, new int[] {5, 4, 3})));
    }
}

Running it prints:

Output
[-1, 3, -1]
[4, -1, 4]
[2, 3, 4, -1]
[-1, -1, -1]

The first two lines, [-1, 3, -1] and [4, -1, 4], answer the two examples. In the second line, the -1 belongs to 7, the number still waiting at the end of the picture.

The third line comes from [1, 2, 3, 4]. Every number is answered by the very next one, so the stack never holds more than one number, and only 4, the last, gets -1. The last line is the other extreme. In [5, 4, 3] each number is smaller than the one before, so nothing is ever taken off the stack, and every answer is -1.

The original implementation, NextGreaterElement1.java, is on GitHub.

Complexity

The work is one pass over nums2, plus one map lookup for each number of nums1.

  • Time: O(m + n), where m is the length of nums1 and n the length of nums2. Each number of nums2 is pushed once and popped at most once, and each lookup in the HashMap takes constant time on average.
  • Space: O(n). The stack and the nextGreater map each hold at most n numbers. The array result is the output.

The same monotonic stack solves Daily Temperatures, which asks how many days later a warmer day comes rather than for the warmer temperature itself.