The next greater element
The classic problem is Daily Temperatures: given daily temperatures, return for each day how many days you have to wait for a warmer temperature (0 if never).
temps = [73, 74, 75, 71, 69, 72, 76, 73]
answer = [ 1, 1, 4, 2, 1, 1, 0, 0]Picture people standing in a line, waiting for someone taller to arrive. Each new person looks back at the people still waiting: everyone shorter than them has found their answer (“the next taller person is me”) and leaves the line. Then the new person starts waiting too.
The people still waiting are always in decreasing order of height, because anyone shorter than a later person would already have left. That’s why it’s called a monotonic stack: its values only go one way.
For Daily Temperatures:
- The stack holds the indexes of days still waiting for a warmer day.
- For each new day
i, while the day on top of the stack is colder, pop it: its answer isi − thatDay. - Then push
i.
Days left on the stack at the end never got a warmer day, so their answer stays 0.
A monotonic stack maintains candidates in sorted order of value so that each new element resolves (pops) all candidates it dominates. For “next greater to the right”, scan left to right with a decreasing stack of indices; each pop assigns the popped index its answer. Variants: next smaller (increasing stack), previous greater/smaller (the element left on top after popping, or scan right to left), strict vs non-strict comparisons for duplicates, and circular arrays (iterate 2n indices modulo n). Amortized O(n): every index is pushed once and popped at most once, however the inner while loop is distributed. Storing indices, not values, gives distances and lets you look values up.
func dailyTemperatures(_ temps: [Int]) -> [Int] {
var answer = Array(repeating: 0, count: temps.count)
var stack: [Int] = [] // indexes of days still waiting for a warmer day
for (i, t) in temps.enumerated() {
while let day = stack.last, temps[day] < t {
stack.removeLast()
answer[day] = i - day // day i is the first warmer one
}
stack.append(i)
}
return answer
}fun dailyTemperatures(temps: IntArray): IntArray {
val answer = IntArray(temps.size)
val stack = ArrayDeque<Int>() // indexes of days still waiting for a warmer day
for (i in temps.indices) {
while (stack.isNotEmpty() && temps[stack.last()] < temps[i]) {
val day = stack.removeLast()
answer[day] = i - day // day i is the first warmer one
}
stack.addLast(i)
}
return answer
}int[] dailyTemperatures(int[] temps) {
int[] answer = new int[temps.length];
Deque<Integer> stack = new ArrayDeque<>(); // indexes of days still waiting for a warmer day
for (int i = 0; i < temps.length; i++) {
while (!stack.isEmpty() && temps[stack.peek()] < temps[i]) {
int day = stack.pop();
answer[day] = i - day; // day i is the first warmer one
}
stack.push(i);
}
return answer;
}function dailyTemperatures(temps: number[]): number[] {
const answer = new Array<number>(temps.length).fill(0);
const stack: number[] = []; // indexes of days still waiting for a warmer day
for (let i = 0; i < temps.length; i++) {
while (stack.length > 0 && temps[stack[stack.length - 1]] < temps[i]) {
const day = stack.pop()!;
answer[day] = i - day; // day i is the first warmer one
}
stack.push(i);
}
return answer;
}Trace the first days of the example:
| Day i | Temp | Pops (answers) | Stack after (temps) |
|---|---|---|---|
| 0 | 73 | – | [73] |
| 1 | 74 | day 0 → 1 | [74] |
| 2 | 75 | day 1 → 1 | [75] |
| 3 | 71 | – | [75, 71] |
| 4 | 69 | – | [75, 71, 69] |
| 5 | 72 | day 4 → 1, day 3 → 2 | [75, 72] |
| 6 | 76 | day 5 → 1, day 2 → 4 | [76] |
| 7 | 73 | – | [76, 73] |
Days 6 and 7 are still waiting at the end, so their answers stay 0. The stack’s temperatures always go down from bottom to top.
Tap the line with the bug.
for (i, t) in temps.enumerated() {
if let day = stack.last, temps[day] < t {
stack.removeLast()
answer[day] = i - day
}
stack.append(i)
}for (i in temps.indices) {
if (stack.isNotEmpty() && temps[stack.last()] < temps[i]) {
val day = stack.removeLast()
answer[day] = i - day
}
stack.addLast(i)
}for (int i = 0; i < temps.length; i++) {
if (!stack.isEmpty() && temps[stack.peek()] < temps[i]) {
int day = stack.pop();
answer[day] = i - day;
}
stack.push(i);
}for (let i = 0; i < temps.length; i++) {
if (stack.length > 0 && temps[stack[stack.length - 1]] < temps[i]) {
const day = stack.pop()!;
answer[day] = i - day;
}
stack.push(i);
}Hint: On day 5 (72°), two earlier days are colder. How many does this code resolve?
An if pops at most one waiting day per new day. On day 5 (72°), days 4 (69°) and 3 (71°) are both colder, but only day 4 gets its answer; day 3 stays on the stack, under a warmer day, and later gets a wrong, larger answer (or 0). The stack is no longer sorted, which breaks the whole idea.
A new value must resolve every waiting position it beats: use while.
Next Greater Element I
nums1 is a subset of nums2 (all values distinct). For each value in nums1, find the first greater value to its right in nums2, or −1.
nums1 = [4, 1, 2], nums2 = [1, 3, 4, 2] → [-1, 3, -1]›
Run the monotonic stack over nums2 once, recording in a map: value → its next greater value.
›
Here you can store values instead of indexes, because you need the next greater value, not a distance, and values are distinct.
SolutionTry it yourself firstTime O(n + m)Space O(n)
func nextGreaterElement(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
var next: [Int: Int] = [:]
var stack: [Int] = []
for n in nums2 {
while let top = stack.last, top < n {
next[stack.removeLast()] = n
}
stack.append(n)
}
return nums1.map { next[$0] ?? -1 }
}fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray {
val next = HashMap<Int, Int>()
val stack = ArrayDeque<Int>()
for (n in nums2) {
while (stack.isNotEmpty() && stack.last() < n) next[stack.removeLast()] = n
stack.addLast(n)
}
return IntArray(nums1.size) { next[nums1[it]] ?: -1 }
}int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer, Integer> next = new HashMap<>();
Deque<Integer> stack = new ArrayDeque<>();
for (int n : nums2) {
while (!stack.isEmpty() && stack.peek() < n) next.put(stack.pop(), n);
stack.push(n);
}
int[] result = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) result[i] = next.getOrDefault(nums1[i], -1);
return result;
}function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
const next = new Map<number, number>();
const stack: number[] = [];
for (const n of nums2) {
while (stack.length > 0 && stack[stack.length - 1] < n) next.set(stack.pop()!, n);
stack.push(n);
}
return nums1.map((v) => next.get(v) ?? -1);
}Why the nested loop is still O(n)
Predict the output
dailyTemperatures runs on n = 1,000,000 days, sorted from hottest to coldest except the last day, which is the hottest of all. How many pops does the last day cause, and what's the total work?
Until the last day nothing is popped (each day is colder than the previous one), so the stack grows to 999,999 indexes. The last day then pops all of them. That single iteration is expensive, but across the whole run there are exactly n pushes and at most n pops: 2n stack operations. That's amortized analysis: count operations per element, not per iteration of the outer loop.
Variants
| Question | Scan | Stack order | Answer comes from |
|---|---|---|---|
| Next greater to the right | left → right | decreasing | the element that pops you |
| Next smaller to the right | left → right | increasing | the element that pops you |
| Previous greater to the left | left → right | decreasing | the top after popping smaller ones |
| Circular array | 2n steps, i % n | as above | push only in the first pass |
- Next greater (right): left-to-right scan, decreasing stack of indices,
while top < current: pop and answer. Next smaller: increasing stack. - Previous greater/smaller: the stack top after popping; circular: iterate 2n with
i % n. - Amortized O(n): each index pushed once, popped at most once; O(n) space worst case.
while, notif; decide strict vs non-strict comparison for duplicates.
Check this part
In Daily Temperatures, what does the stack contain?
Why must the pop be a while loop?
The inner while loop can pop many elements. Why is the total still O(n)?
For the next smaller element to the right, which stack do you keep?