Notes
All notes

Stacks (LeetCode #3)

A stack is the data structure for nested things: brackets that must close in reverse order, an undo history, a call stack, or a series of values where each new one resolves the ones before it. Its power is that the most recent unfinished item is always the next one to deal with. This post covers the seven NeetCode Stack problems, each restated and walked by hand.

The technique

A stack gives push (add on top), pop (remove the top), and peek (look at the top), all \(O(1)\). Use it when the last thing added is the first that must be resolved.

Monotonic stack. Keep the stack sorted (say decreasing by value). When a new element is larger than the top, it is the answer for all the smaller elements it pops:

def next_greater(nums):
    res = [-1] * len(nums)
    stack = []                       # INDICES, values decreasing
    for i, x in enumerate(nums):
        while stack and nums[stack[-1]] < x:
            res[stack.pop()] = x
        stack.append(i)
    return res

Each index is pushed once and popped at most once, so the whole pass is \(O(n)\).

Valid Parentheses

The question. Given a string of brackets ()[]{}, return True if every opener is closed by the matching type in the correct order.

Input:  "()[]{}"  -> True
Input:  "([)]"    -> False        (crossed order)

The idea. The most recently opened bracket must close first — a stack. Push openers; on a closer, the top must match; the stack must be empty at the end.

Walk it through "([{}])": push (, [, {; on } top { matches, pop; on ] top [ matches, pop; on ) top ( matches, pop; empty → True.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
  \foreach \v [count=\i from 0] in {(,[,\{} { \node[c, fill=blue!8] at (\i*0.66,0.9) {\v}; }
  \node[c, fill=green!15] at (1.32,0) {(};
  \draw[->, thick] (0.66,0.6) -- (1.1,0.3);
  \draw[->, thick] (1.32,0.6) -- (1.32,0.3);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0.99,-0.55) {close must match the top};
\end{tikzpicture}
PAIRS = {")": "(", "]": "[", "}": "{"}

def is_valid(s):
    stack = []
    for ch in s:
        if ch in "([{":
            stack.append(ch)
        elif ch in PAIRS:
            if not stack or stack.pop() != PAIRS[ch]:
                return False
    return not stack

\(O(n)\) time and space.

Min Stack

The question. Design a stack with push, pop, top, and get_min, all \(O(1)\).

push(5); push(3); get_min() -> 3; push(7); pop(); get_min() -> 3

The idea. A single min variable fails when you pop the minimum. Keep a second stack of running minimums: each push also records the new minimum.

Walk it through pushing 5, 3, 7: data = [5,3,7], mins = [5,3,3]. get_min is mins[-1].

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
  \foreach \v [count=\i from 0] in {5,3,7} { \node[c, fill=blue!8] at (\i*0.66,0.9) {\v}; }
  \foreach \v [count=\i from 0] in {5,3,3} { \node[c, fill=orange!15] at (\i*0.66,0) {\v}; }
  \node[font=\scriptsize\ttfamily, anchor=east] at (-0.4,0.9) {data};
  \node[font=\scriptsize\ttfamily, anchor=east] at (-0.4,0) {mins};
\end{tikzpicture}
class MinStack:
    def __init__(self):
        self.data, self.mins = [], []
    def push(self, x):
        self.data.append(x)
        self.mins.append(x if not self.mins else min(x, self.mins[-1]))
    def pop(self):
        self.mins.pop(); return self.data.pop()
    def top(self):
        return self.data[-1]
    def get_min(self):
        return self.mins[-1]

Invariant: mins[-1] == min(data). \(O(1)\) per op; see Min Stack.

Evaluate Reverse Polish Notation

The question. Evaluate an arithmetic expression in postfix (reverse Polish) notation, where operators follow their operands.

Input:  ["2", "1", "+", "3", "*"]
Output: 9           ((2 + 1) * 3)

The idea. Operands are pushed; an operator pops its two operands, applies, and pushes the result. Because operands always come before their operator, the stack always has what it needs.

Walk it through on ["2","1","+","3","*"]: push 2; push 1; + pops 1 and 2 → push 3; push 3; * pops 3 and 3 → push 9. Answer 9.

Order matters. Subtraction and division are not commutative, so the first pop is the right operand and the second is the left: a = pop(); b = pop(); result = b op a.

import math

def eval_rpn(tokens):
    stack = []
    for tok in tokens:
        if tok in "+-*/":
            a = stack.pop()                # right operand
            b = stack.pop()                # left operand
            if tok == "+": stack.append(b + a)
            elif tok == "-": stack.append(b - a)
            elif tok == "*": stack.append(b * a)
            else: stack.append(int(b / a))  # truncate toward zero
        else:
            stack.append(int(tok))
    return stack[0]

Why int(b / a)? The problem requires truncation toward zero, not floor; Python’s // floors negatives, so use int() of true division.

\(O(n)\) time and space.

Generate Parentheses

The question. Given n, return all well-formed strings of n pairs of parentheses.

Input:  n = 3
Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]

The idea. Backtrack: you may add ( if fewer than n are open, and ) only if there is an unmatched (, i.e. close < open. This never builds an invalid prefix.

Walk it through for n = 2: (( → (() → (()); back up, () → ()( → ()().

def generate(n):
    out, path = [], []
    def backtrack(open_, close):
        if len(path) == 2 * n:
            out.append("".join(path)); return
        if open_ < n:
            path.append("("); backtrack(open_ + 1, close); path.pop()
        if close < open_:
            path.append(")"); backtrack(open_, close + 1); path.pop()
    backtrack(0, 0)
    return out

\(O(4^n / n^{3/2})\) (Catalan count). The close < open_ guard is the pruning.

Daily Temperatures

The question. For each day, return how many days until a warmer day, or 0 if none.

Input:  [73, 74, 75, 71, 69, 72, 76, 73]
Output: [1, 1, 4, 2, 1, 1, 0, 0]

The idea. “Next greater element.” Keep a monotonic stack of indices with temperatures still waiting for a warmer day. A new warmer temperature resolves every colder day on the stack.

Walk it through from earlier: 74 answers 73 (1 day), 75 answers 74, 76 answers 75 (4 days), 72 (1), 69 (2).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
  \foreach \v [count=\i from 0] in {73,74,75,76,72,69} { \node[c, fill=blue!8] at (\i*0.66,0) {\v}; }
  \draw[->, thick, green!55!black] (0.33,0.28) to[bend left=25] (0.99,0.28);
  \draw[->, thick, green!55!black] (0.99,0.28) to[bend left=25] (1.65,0.28);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (1.65,-0.55) {a warmer day pops all colder days below it};
\end{tikzpicture}
def daily_temperatures(temps):
    res = [0] * len(temps)
    stack = []                       # indices, temps decreasing
    for i, t in enumerate(temps):
        while stack and temps[stack[-1]] < t:
            j = stack.pop()
            res[j] = i - j
        stack.append(i)
    return res

\(O(n)\) amortized time, \(O(n)\) space.

Car Fleet

The question. Cars drive toward a target on a single-lane road; each has a position and speed. A faster car catching a slower one cannot pass, so they form a fleet and arrive together. Count the fleets that reach the target.

Input:  target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
Output: 3

The idea. Work backwards from the target. For each car compute the time it needs to reach the target: (target - position) / speed. Sort cars by position descending (closest first). The car closest to the target leads its fleet; any later car whose time is no smaller is slower or equal, so it arrives behind and forms a new fleet. If a car’s time is smaller, it catches the fleet ahead and joins it.

Walk it through. Times: car at 10 → (12-10)/2 = 1; at 8 → 4/4 = 1; at 5 → 7/1 = 7; at 3 → 9/3 = 3; at 0 → 12/1 = 12. Sorting by position desc: 10 (t=1), 8 (t=1), 5 (t=7), 3 (t=3), 0 (t=12). Fleets: 10 leads (1); 8 has t=1, not smaller → new fleet (2); 5 has t=7 > 1 → new fleet (3); 3 has t=3 (and 7 is the current fleet time 7? only compare to the last fleet’s time) — 3 joins the 7-fleet; 0 has t=12 > 7 → new fleet. Total 3.

def car_fleet(target, position, speed):
    cars = sorted(zip(position, speed), reverse=True)   # closest first
    fleets = 0
    last_time = 0
    for pos, spd in cars:
        time = (target - pos) / spd
        if time > last_time:        # cannot catch the fleet ahead -> new fleet
            fleets += 1
            last_time = time
    return fleets

Why it works. Processing from the target outward, a car either catches the fleet it is behind (time ≤ that fleet’s time) or leads a new one. last_time is the arrival time of the most recently formed fleet.

\(O(n \log n)\) time (sort), \(O(n)\) space.

Largest Rectangle in Histogram

The question. Find the largest rectangle that fits under a bar chart.

Input:  [2, 1, 5, 6, 2, 3]
Output: 10        (bars 5 and 6: width 2 × height 5)

The idea. For each bar, the biggest rectangle using that bar’s height extends until it hits a shorter bar. So we need each bar’s nearest shorter bar on each side — a monotonic stack in one pass.

Walk it through. Bar 5 is followed by 6, then 2 (shorter), so 5 spans width 2 → area 10; bar 6 spans width 1 → 6. Nothing beats 10.

\begin{tikzpicture}[font=\rmfamily, >=stealth]
  \foreach \h [count=\i from 0] in {2,1,5,6,2,3} { \draw[thick, fill=blue!20] (\i*0.5,0) rectangle (\i*0.5+0.4,\h*0.22); }
  \draw[very thick, orange!80!black, rounded corners=2pt] (0.95,-0.05) rectangle (1.95,1.15);
  \node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (1.45,-0.15) {5 x 2 = 10};
\end{tikzpicture}
def largest_rectangle(heights):
    stack = []                       # (start_index, height), increasing
    best = 0
    for i, h in enumerate(heights + [0]):   # sentinel flushes the stack
        start = i
        while stack and stack[-1][1] > h:
            idx, ht = stack.pop()
            best = max(best, ht * (i - idx))
            start = idx
        stack.append((start, h))
    return best

Why the sentinel 0? It is shorter than every bar, so it forces all remaining bars to be resolved at the end.

\(O(n)\) time and space.

Pitfalls

QQuestionSelf-check

Why is a monotonic stack \(O(n)\) despite the inner while? How does Car Fleet use the target time?

ASolution

Each index is pushed once and popped at most once. Car Fleet computes each car’s arrival time and processes cars from the target outward: if a car’s time is no larger than the fleet ahead, it catches it and joins; otherwise it starts a new fleet.

Next: Binary Search (LeetCode #4) — halving the space, and searching on the answer.