Stack
Think of a stack of plates. You only ever touch the top one, and the last plate you put down is the first one you pick up.
2 · Watch
Stack in 60 seconds
3 · Now you drive
Valid Parentheses
4 · Your turn
Start from this
// Items still waiting for their answer.
const stack: number[] = [];
for (const x of items) {
// Pop every item that x settles.
while (stack.length && shouldPop(stack.at(-1)!, x)) {
resolve(stack.pop()!, x);
}
// x now waits for its own answer.
stack.push(x);
}Easy ways to go wrong
- Popping from an empty stack. Check it first.
- Forgetting what’s still on the stack when the loop ends.
- Storing values when you’ll need indices later.
- Pushing before popping. Settle the older items first, then push the new one.
- Getting the order wrong. Decide up front whether the stack rises or falls from bottom to top.
Matching pairs
The newest open item is the first one to close.
- Easy01
Valid Parentheses
The one you just watched. Write it from memory.
The newest open bracket must close first: last in, first out.
- Time
- O(n)
- Space
- O(n)
Parsing
Save what you have when a new level opens, and finish it when the level closes.
- Medium02
Decode String
Push what you have at each [ and rebuild it at each ].
Brackets nest, and the innermost one has to be expanded first.
- Time
- O(output)
- Space
- O(output)
O(output) time · O(output) spacefunction decodeString(s: string): string { // What came before each open bracket, and how many times to repeat what's inside. const stack: [string, number][] = []; let current = ""; let count = 0; for (const ch of s) { if (ch >= "0" && ch <= "9") { // Counts can have more than one digit. count = count * 10 + Number(ch); } else if (ch === "[") { stack.push([current, count]); current = ""; count = 0; } else if (ch === "]") { // The innermost bracket closes first. const [before, times] = stack.pop()!; current = before + current.repeat(times); } else { current += ch; } } return current; } - Medium03
Basic Calculator II
Hold terms on the stack. * and / fold into the top one at once.
* and / come before + and -, so keep each term until you know its sign.
- Time
- O(n)
- Space
- O(n)
O(n) time · O(n) spacefunction calculate(s: string): number { // Terms to add up at the end. * and / fold into the last term straight away. const stack: number[] = []; let num = 0; let op = "+"; for (let i = 0; i < s.length; i++) { const ch = s[i]; const digit = ch >= "0" && ch <= "9"; if (digit) num = num * 10 + Number(ch); // An operator, or the last character, settles the number before it. if ((!digit && ch !== " ") || i === s.length - 1) { if (op === "+") stack.push(num); else if (op === "-") stack.push(-num); else if (op === "*") stack.push(stack.pop()! * num); // Division rounds toward zero. else stack.push(Math.trunc(stack.pop()! / num)); op = ch; num = 0; } } return stack.reduce((sum, term) => sum + term, 0); }
Monotonic stack
Keep the stack in order. Each new value pops every item it answers.
- Medium04
Daily Temperatures
Same stack, but each new day pops every colder day it answers.
Each day waits until a warmer one arrives. The newest waiting day is answered first.
- Time
- O(n)
- Space
- O(n)
O(n) time · O(n) spacefunction dailyTemperatures(temps: number[]): number[] { const out = new Array(temps.length).fill(0); // Days still waiting for a warmer one, coldest on top. const stack: number[] = []; for (let i = 0; i < temps.length; i++) { // Today answers every colder day on top. while (stack.length && temps[i] > temps[stack.at(-1)!]) { const day = stack.pop()!; out[day] = i - day; } stack.push(i); } // Days left on the stack never get warmer, so they stay 0. return out; } - Hard05
Largest Rectangle in Histogram
Keep bars rising. A shorter bar ends every taller rectangle before it.
A bar’s rectangle stops at the first shorter bar on each side.
- Time
- O(n)
- Space
- O(n)
O(n) time · O(n) spacefunction largestRectangleArea(heights: number[]): number { // Indices of bars in rising height order. const stack: number[] = []; let best = 0; for (let i = 0; i <= heights.length; i++) { // A height-0 bar past the end pops everything still waiting. const h = i < heights.length ? heights[i] : 0; while (stack.length && h < heights[stack.at(-1)!]) { const height = heights[stack.pop()!]; // The popped bar stretches from just after the new top to just before i. const left = stack.length ? stack.at(-1)! + 1 : 0; best = Math.max(best, height * (i - left)); } stack.push(i); } return best; } - Hard06
Trapping Rain Water
Same popping, but each pop fills one layer of water.
Water sits in a dip until a taller bar on the right closes it.
- Time
- O(n)
- Space
- O(n)
Also works with Two Pointers.
O(n) time · O(n) spacefunction trap(height: number[]): number { // Bars that could still be the left wall of a pool, falling to the top. const stack: number[] = []; let water = 0; for (let i = 0; i < height.length; i++) { // A taller bar closes the dip on top of the stack. while (stack.length && height[i] > height[stack.at(-1)!]) { const floor = stack.pop()!; // No wall on the left, so this water runs off. if (!stack.length) break; const left = stack.at(-1)!; // Fill one layer: from the floor up to the lower wall. const depth = Math.min(height[left], height[i]) - height[floor]; water += depth * (i - left - 1); } stack.push(i); } return water; } - Hard07
Sliding Window Maximum
A queue this time: drop from the back like a stack, expire from the front.
A new value makes every smaller one before it useless, so drop them from the back.
- Time
- O(n)
- Space
- O(k)
Also works with Sliding Window or Heaps.
O(n) time · O(k) spacefunction maxSlidingWindow(nums: number[], k: number): number[] { // Indices whose values fall from front to back, so the front is the max. const queue: number[] = []; // Where the front is. Moving it is O(1), unlike shift(). let head = 0; const out: number[] = []; for (let i = 0; i < nums.length; i++) { // Smaller values before nums[i] can never be the max again. while (queue.length > head && nums[queue.at(-1)!] <= nums[i]) queue.pop(); queue.push(i); // The front has slid out of the window. if (queue[head] <= i - k) head++; if (i >= k - 1) out.push(nums[queue[head]]); } return out; }