Skip to content
DSA in JavaScript
← All patterns

Monotonic Stack

0/20 solved

What it is

A stack that you keep sorted (always increasing or always decreasing) by popping items that can no longer be the answer. Each item is pushed and popped once.

Used for

"Next greater element", daily temperatures, largest rectangle in a histogram.
nums
2
1
5
3
6
answer
?
?
?
?
?
stack

Step 1 of 7

Goal: for each number, find the next bigger number to its right. Comparing every number with everything after it is slow. Instead keep a stack of numbers that are still waiting for a bigger one.

You see

  • Next greater or smaller element
  • Nesting, brackets, undo
  • Largest rectangle or span problems

Learn it in

StackValid Parentheses ProblemRain Terraces (Trapping Rain Water) Problem

Template

function nextGreater(a) {  const out = Array(a.length).fill(-1), st = [];  for (let i = 0; i < a.length; i++) {    while (st.length && a[st.at(-1)] < a[i]) out[st.pop()] = a[i];    st.push(i);  }  return out;}

Practice problems