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, nums1nums2nums1nums2nums1nums2nums1
Example 1
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
Output: [4, -1, 4]
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
nums1 = [3, 7, 1]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
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 nums2nums1
Answering every number of nums2
Why answer all of nums2nums1nums1nums2nums1nums2nums2nums1
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. ArrayDequejava.utilpeekpoppushStackDequeArrayDeque
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 nums1HashMapnums2
Numbers still on the stack at the end never got an answer, so they are not in the map. getOrDefault(key, -1)
Java Solution
The method nextGreaterElement
- First, create the map
for the answers and annextGreater calledArrayDeque for the waiting numbers.stack - Read
from left to right with a loop, one numbernums2 at a time. Inside, ax loop takes numbers offwhile as long as the newest one,stack , is smaller thanstack.peek() , and storesx inx as the answer of each one.nextGreater - Then push
ontox , where it waits for its own answer.stack - After the loop, create the array
, as long asresult . A second loop fills it: for eachnums1 ,nums1[i] gives its answer, or -1 if it never got one.nextGreater.getOrDefault(nums1[i], -1) - Return
.result
The mainnums2
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:
[-1, 3, -1]
[4, -1, 4]
[2, 3, 4, -1]
[-1, -1, -1]
The first two lines, [-1, 3, -1][4, -1, 4]
The third line comes from [1, 2, 3, 4][5, 4, 3]
The original implementation,
Complexity
The work is one pass over nums2nums1
- Time: O(m + n), where m is the length of
and n the length ofnums1 . Each number ofnums2 is pushed once and popped at most once, and each lookup in thenums2 takes constant time on average.HashMap - Space: O(n). The stack and the
map each hold at most n numbers. The arraynextGreater is the output.result
The same monotonic stack solves