Next Greater Element I
Easy
Topics
a is a subset of b, and all values in both arrays are distinct.
For each value in a, find where it occurs in b and report the first value to the right of it in b that is greater than it. If there is no such value, report -1.
Return the answers in the same order as a.
Example 1
a is looked up in b, and the answer is the first value to the right of it in b that is larger — position in b is what matters, not position in a. Here 2 values have nothing larger after them, which is what the -1s mark.Input: a = [4,1,2], b = [1,3,4,2] Output: [-1,3,-1] Explanation: Nothing right of 4 in b is bigger. Right of 1 comes 3. Right of 2 there is nothing at all.
Example 2
Input: a = [2,4], b = [1,2,3,4] Output: [3,-1] Explanation: 3 follows 2; 4 is last in b.
Example 3
Input: a = [1], b = [1] Output: [-1] Explanation: A single element has nothing to its right.
Constraints
- 1 <= a.length <= b.length <= 1000
- 0 <= a[i], b[i] <= 10^4
- All values in a and b are unique
- Every value in a also appears in b
Editorial — intuition, approach, complexity and pitfalls
Intuition
The brute force is to locate each value in b and then scan rightwards for something larger, which re-walks the same tail of b over and over.
The observation that removes the rescanning: process b once, left to right, holding the values whose answer is still unknown. When a new value arrives it is the answer for every held value smaller than it — and it answers them in order, because the held values are necessarily in decreasing order. A value can only be waiting if everything that came before it and was smaller has already been answered.
So the holding structure is a stack that never contains an increasing pair, and each value is pushed once and popped once. The answers come out as b is scanned, independently of a, so the last step is a lookup.
Approach
- Keep a stack of values from
bwhose next-greater is not yet known, and a map from value to answer. - Scan
b. While the stack is non-empty and its top is smaller than the current value, pop it and record the current value as its answer. - Push the current value. Anything left on the stack at the end has no greater value to its right.
- Read the answers for
aout of the map, defaulting to-1for values still on the stack.
Walkthrough
b = [1, 3, 4, 2]
value stack before pops and answers stack after
1 [] -- [1]
3 [1] 1 -> 3 [3]
4 [3] 3 -> 4 [4]
2 [4] 4 is bigger, no pop [4, 2]
left on the stack: 4 and 2, so both answer -1
map: {1: 3, 3: 4, 4: -1, 2: -1}
a = [4, 1, 2] -> [-1, 3, -1]Complexity
- Time — O(n + m): every element of b is pushed once and popped at most once, then one lookup per element of a. The nested scan is O(n * m).
- Space — O(m): the stack and the answer map, both bounded by the size of b.
Common Pitfalls
- Searching the whole of
brather than only the part to the right of the value’s own position. The first greater value anywhere is not the answer. - Keeping the stack in increasing order. It has to be decreasing from the bottom, which is what the pop loop maintains.
- Forgetting the values still on the stack at the end. They are exactly the ones with no answer, and they need
-1. - Using
<=in the pop test. The values are distinct so it makes no difference here, but it does in the variants where they are not.
Full Solution — all languages
class Solution:
def nextGreaterElement(self, a, b):
answer = {}
stack = []
for value in b:
while stack and stack[-1] < value:
answer[stack.pop()] = value
stack.append(value)
return [answer.get(value, -1) for value in a]import java.util.*;
class Solution {
public int[] nextGreaterElement(int[] a, int[] b) {
Map<Integer, Integer> answer = new HashMap<>();
Deque<Integer> stack = new ArrayDeque<>();
for (int value : b) {
while (!stack.isEmpty() && stack.peek() < value) {
answer.put(stack.pop(), value);
}
stack.push(value);
}
int[] out = new int[a.length];
for (int i = 0; i < a.length; i++) out[i] = answer.getOrDefault(a[i], -1);
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> nextGreaterElement(vector<int>& a, vector<int>& b) {
unordered_map<int, int> answer;
vector<int> stack;
for (int value : b) {
while (!stack.empty() && stack.back() < value) {
answer[stack.back()] = value;
stack.pop_back();
}
stack.push_back(value);
}
vector<int> out;
for (int value : a) {
auto it = answer.find(value);
out.push_back(it == answer.end() ? -1 : it->second);
}
return out;
}
};/**
* @param {number[]} a
* @param {number[]} b
* @return {number[]}
*/ var nextGreaterElement = function(a, b) {
const answer = new Map();
const stack = [];
for (const value of b) {
while (stack.length && stack[stack.length - 1] < value) {
answer.set(stack.pop(), value);
}
stack.push(value);
}
return a.map(v => (answer.has(v) ? answer.get(v) : -1));
};