For each position i, find the smallest j > i with a[j] > a[i] (or -1). Nested loops are O(n²) and die at n = 2·10⁵. The structure is a monotonic stack of indices whose values are decreasing (for *strictly greater*).
Invariant: the stack is decreasing by value. When a[i] arrives, pop while the top is smaller than a[i] — those popped indices have just found their next greater (i). Then push i.
CSES Nearest Smaller Values is the twin with a greater-to-smaller flip. USACO Gold 'Stacks' is this lesson.
function nextGreater(a) {
const n = a.length;
const ans = Array(n).fill(-1);
const st = []; // indices, values decreasing
for (let i = 0; i < n; i++) {
while (st.length && a[st[st.length - 1]] < a[i]) {
ans[st.pop()] = a[i];
}
st.push(i);
}
return ans;
}Checks 0/2