A stack kept in decreasing order that answers 'next greater element' for every item in one linear pass.
A monotonic stack answers the question *'for each element, what's the next larger value to its right?'* for every element in a single pass. The stack holds elements still waiting for an answer, kept in decreasing order from bottom to top. When a new value arrives, it pops everything smaller than itself — and each popped element has just found its next greater element: the new value.
An element on the stack is one that hasn't yet seen anything bigger to its right. Keeping the stack strictly decreasing means the moment a bigger value appears, all the smaller values sitting above are *resolved at once*. Then the new value is pushed to wait for its own next-greater. Nothing ever gets scanned twice.
-1.2: stack empty → push. Stack (values): [2].1: 1 < 2 → push. Stack: [2, 1].2: 2 > 1 → pop 1, its answer is 2. Now top is 2, not strictly less → push. Stack: [2, 2].4: 4 > 2 → pop, answer 4. 4 > 2 → pop, answer 4. Empty → push. Stack: [4].3: 3 < 4 → push. Stack: [4, 3].4 and 3 remain → both answer -1. Result: [4, 2, 4, -1, -1].function nextGreater(arr) {
const res = new Array(arr.length).fill(-1);
const stack = []; // holds indices, values decreasing
for (let i = 0; i < arr.length; i++) {
while (stack.length && arr[i] > arr[stack[stack.length - 1]]) {
res[stack.pop()] = arr[i]; // i is the next greater
}
stack.push(i);
}
return res;
}
// nextGreater([2, 1, 2, 4, 3]) === [4, 2, 4, -1, -1]