Next Greater Element I
Pattern: Monotonic stack
Scan nums2 with a stack of values still waiting for something greater. A new value pops every smaller waiter and is their answer. Store the answers in a map, then look up each value of nums1.
The problem
nums1 is a subset of nums2, and all values are different. For each value of nums1, find it in nums2 and return
the first greater value to its right there, or -1. nums1 = [4, 1, 2], nums2 = [1, 3, 4, 2] gives [-1, 3, -1].
Think first
- For one value, how would you find its next greater by hand?
- When a big value arrives, which earlier values does it answer?
- How do you connect the answers back to nums1?
Hints
Brute force, and why it fails
For each value of nums1, find it in nums2 and scan right: O(m × n).
The key insight
The values still waiting always decrease from bottom to top, so a new value pops exactly those it answers, from the top.
Dry run
10i
31
42
23
| stack | 1 |
|---|
nums2 = [1, 3, 4, 2]. Push 1.
Step 1 of 4
The plan
next = {}; stack = []
for v in nums2:
while stack and top < v: next[pop] = v
push v
return [next.get(x, -1) for x in nums1]
Complexity
- Time
O(m + n)- Space
O(n)
Each value of nums2 is pushed and popped once; each lookup is O(1).
Edge cases
- The last value of
nums2: always-1. - Decreasing
nums2: every answer-1. - One value.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer, Integer> next = new HashMap<>(); // value -> next greater value in nums2
Deque<Integer> st = new ArrayDeque<>(); // values still waiting, decreasing from bottom to top
for (int v : nums2) {
while (!st.isEmpty() && st.peek() < v) next.put(st.pop(), v); // v is the answer for every smaller waiter
st.push(v);
}
int[] out = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) out[i] = next.getOrDefault(nums1[i], -1);
return out;
}
}C++
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int, int> next; // value -> next greater value in nums2
stack<int> st; // values still waiting, decreasing from bottom to top
for (int v : nums2) {
while (!st.empty() && st.top() < v) { next[st.top()] = v; st.pop(); } // v answers smaller waiters
st.push(v);
}
vector<int> out;
for (int x : nums1) out.push_back(next.count(x) ? next[x] : -1);
return out;
}
};Python
class Solution:
def nextGreaterElement(self, nums1: list[int], nums2: list[int]) -> list[int]:
nxt, st = {}, [] # value -> next greater; waiting values, decreasing
for v in nums2:
while st and st[-1] < v:
nxt[st.pop()] = v # v is the answer for every smaller waiter
st.append(v)
return [nxt.get(x, -1) for x in nums1]Common mistakes
- Searching
nums2again for every value ofnums1instead of using the map. - Returning the index of the greater value instead of the value.