Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

Parsing Expressions with Stacks

Shunting-yard, postfix evaluation and stack machines.

Type 2+3×42 + 3 \times 4 into a calculator and it answers 14, not 20. You know that ×\times binds more tightly than ++; a program must work it out from a flat row of tokens. In 1961 Edsger Dijkstra showed that one stack of waiting operators and a single left-to-right pass are enough, and the same stack still sits inside compilers' expression parsers and bytecode virtual machines.

What you’ll learn

  • Define infix, prefix and postfix notation as walks of an expression tree, and prove that a postfix string determines its tree without any parentheses.
  • Run Dijkstra's shunting-yard algorithm with precedence and associativity, and prove that it runs in linear time.
  • Write a Pratt (top-down operator precedence) parser with binding powers, and see the call stack play the role of the operator stack.
  • Compute the stack depth an expression needs on a stack machine, and prove the bound ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 for a tree with nn leaves.
  • Explain why one stack lifts finite automata exactly to the context-free languages, and what is known about the cost of general context-free parsing.

Three notations, one tree

An arithmetic expression with binary operators is a tree: the leaves are operands and the internal nodes are operators. Writing the tree down as text means choosing a walk:

  • infix, the inorder walk, puts each operator between its operands: (7−2)×(1+4)(7 - 2) \times (1 + 4). It needs parentheses or precedence rules to be unambiguous.
  • prefix, or Polish notation, introduced by the logician Jan Łukasiewicz in the 1920s, is the preorder walk: * - 7 2 + 1 4.
  • postfix, or reverse Polish notation, is the postorder walk: 7 2 - 1 4 + *.

Postfix is what machines like. Evaluate it left to right with one stack: push each operand, and let each operator pop two values and push its result.

DerivationProof: the rank is the height of the stack
  1. height after t1…ti  =  ∑j≤irank⁡(tj)\text{height after } t_1 \dots t_i \;=\; \sum_{j \le i} \operatorname{rank}(t_j)

    Height. Evaluation pushes one value for an operand, and pops two and pushes one for an operator. So after ii tokens the stack holds exactly as many values as the prefix's rank.

  2. height≥1 after every token,height=1 at the end\text{height} \ge 1 \ \text{after every token}, \qquad \text{height} = 1 \ \text{at the end}

    Well formed means the evaluation never fails. An operator needs two values, so the height is at least 2 before it and at least 1 after it; an operand leaves the height at least 1; and a single expression leaves exactly one value. Conversely, when these conditions hold the evaluation succeeds and builds a tree whose postorder walk is the input.

  3. eval⁡(post⁡(L) post⁡(R) ∘)  =  ∘(L,R)\operatorname{eval}\big(\operatorname{post}(L)\ \operatorname{post}(R)\ \circ\big) \;=\; \circ(L, R)

    Uniqueness. Let the stack hold subtrees instead of numbers, so each operator joins the two topmost subtrees. By induction on the tree, evaluating the postorder walk of any tree TT rebuilds TT. The evaluation is deterministic, so two different trees cannot share a postorder walk.

Check your understanding

Which token sequence is a well-formed postfix expression?

  1. 3 4 + 5
  2. 3 + 4 5
  3. 3 4 5 + * 6 -
  4. 3 4 5 + * 6
Show the answer

C. 3 4 5 + * 6 -

Its prefix ranks are 1,2,3,2,1,2,11, 2, 3, 2, 1, 2, 1: never below 1, and exactly 1 at the end. It means 3×(4+5)−6=213 \times (4 + 5) - 6 = 21.

Dijkstra's shunting-yard algorithm

How do you get from infix to postfix? Dijkstra's shunting-yard algorithm, named after a railway yard where wagons wait on a siding, reads the infix tokens once, left to right:

  • an operand goes straight to the output;
  • an operator oo first sends to the output every operator o′o' waiting above the nearest ( that must be applied before it: those with higher precedence than oo, or equal precedence when oo is left-associative. Then oo is pushed;
  • ( is pushed, and ) sends operators to the output until the matching (, which is discarded;
  • at the end, every operator still waiting goes to the output.
python
PREC = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
RIGHT = {'^'}                                  # right-associative operators

def to_postfix(tokens):
    out, ops = [], []
    for t in tokens:
        if t == '(':
            ops.append(t)
        elif t == ')':
            while ops[-1] != '(':
                out.append(ops.pop())
            ops.pop()                          # discard the '('
        elif t in PREC:
            while (ops and ops[-1] != '(' and
                   (PREC[ops[-1]] > PREC[t] or
                    (PREC[ops[-1]] == PREC[t] and t not in RIGHT))):
                out.append(ops.pop())
            ops.append(t)
        else:
            out.append(t)                      # an operand goes straight out
    while ops:
        out.append(ops.pop())
    return out

Tokens are strings. A production parser must also report mismatched parentheses: a ) that empties the stack, or a ( left over at the end. Unary minus needs its own token, chosen from context: a - at the start, after ( or after another operator is unary.

TokenOutput so farOperator stack (top at the right)Why
1010(empty)an operand
-10-nothing waits: push
410 4-an operand
-10 4 --equal precedence, left-associative: the waiting - goes first
210 4 - 2-an operand
*10 4 - 2- ** binds more tightly than -: push
(10 4 - 2- * (push
110 4 - 2 1- * (an operand
+10 4 - 2 1- * ( +nothing above ( to pop: push
210 4 - 2 1 2- * ( +an operand
)10 4 - 2 1 2 +- *pop down to ( and drop it
^10 4 - 2 1 2 +- * ^^ binds more tightly than *: push
210 4 - 2 1 2 + 2- * ^an operand
end10 4 - 2 1 2 + 2 ^ * -(empty)flush the stack
A full trace on 10 - 4 - 2 * ( 1 + 2 ) ^ 2. The output means (10−4)−2×(1+2)2=6−18=−12(10 - 4) - 2 \times (1 + 2)^2 = 6 - 18 = -12.
Think first The pop rule treats equal precedence differently for left- and right-associative operators. With ^ right-associative, what does the algorithm output for 2 ^ 3 ^ 2, and what would it output if it popped on equal precedence regardless?

The second ^ does not pop the first, so the output is 2 3 2 ^ ^, meaning 2(32)=29=5122^{(3^2)} = 2^9 = 512, the mathematical convention. Popping on equality would give 2 3 ^ 2 ^, meaning (23)2=64(2^3)^2 = 64. For a left-associative operator, popping on equality is exactly right: 8 - 3 - 1 must mean (8−3)−1=4(8 - 3) - 1 = 4.

Pratt parsing: the call stack as the operator stack

Many hand-written parsers use recursive descent, and a popular way to handle expressions inside them is top-down operator precedence, due to Vaughan Pratt (1973). Each infix operator gets two binding powers, a left one ll and a right one rr. A call expr(min_bp) parses one operand, then keeps absorbing operators whose left binding power is at least min_bp, parsing each right operand with a recursive call at that operator's right binding power.

Associativity is a matter of a tie-break. A left-associative operator binds slightly more tightly on its right (l<rl < r), so a second copy of it stops the recursion and is applied later, from outside. A right-associative operator binds less tightly on its right (l>rl > r), so the recursion swallows the rest of the chain.

python
BP = {'+': (1, 2), '-': (1, 2), '*': (3, 4), '/': (3, 4), '^': (6, 5)}   # (left, right)

def parse(tokens):
    pos = 0
    def expr(min_bp):
        nonlocal pos
        t = tokens[pos]; pos += 1
        if t == '(':
            lhs = expr(0)
            pos += 1                           # skip ')'
        elif t == '-':
            lhs = ('neg', expr(5))             # unary minus: tighter than *, looser than ^
        else:
            lhs = int(t)
        while pos < len(tokens) and tokens[pos] in BP:
            l, r = BP[tokens[pos]]
            if l < min_bp:
                break                          # the operator belongs to an outer call
            op = tokens[pos]; pos += 1
            lhs = (op, lhs, expr(r))
        return lhs
    return expr(0)

It returns a tree of nested tuples: 2 ^ 3 ^ 2 parses as ('^', 2, ('^', 3, 2)) and 1 - 2 - 3 as ('-', ('-', 1, 2), 3). Unary minus gets binding power 5, so - 2 ^ 2 means −(22)=−4-(2^2) = -4 while - 2 * 3 means (−2)×3(-2) \times 3. On binary operators it builds the same tree as shunting-yard.

Stack machines, and how deep the stack must grow

A stack machine runs postfix code directly: instructions push constants or variables, and operators pop their operands and push results. The Java virtual machine, CPython's bytecode interpreter and WebAssembly are stack machines (WebAssembly's validator even checks the type of every operand-stack slot before the code runs), and so are Forth, PostScript and HP's RPN calculators such as the HP-35 of 1972. Compiling an expression for such a machine is a postorder walk of its tree, and the one resource the code consumes is stack depth.

DerivationProof
  1. max⁡(D(X), 1+D(Y))\max\big(D(X),\ 1 + D(Y)\big)

    The cost of one order. If operand XX is evaluated first, its value occupies one slot during the whole evaluation of the other operand YY. That order needs

  2. min⁡(max⁡(a,1+b), max⁡(b,1+a))={max⁡(a,b)a≠ba+1a=b\min\big(\max(a, 1 + b),\ \max(b, 1 + a)\big) = \begin{cases} \max(a, b) & a \ne b \\ a + 1 & a = b \end{cases}

    The best order evaluates the deeper operand first. If a>ba > b it costs max⁡(a,1+b)=a\max(a, 1 + b) = a; if a=ba = b both orders cost a+1a + 1; and the shallower-first order is never cheaper. By induction on the tree, no code of this kind beats DD:

  3. n ≥ 2D−1⟹D ≤ ⌊log⁡2n⌋+1n \ \ge\ 2^{D - 1} \quad\Longrightarrow\quad D \ \le\ \lfloor \log_2 n \rfloor + 1

    Leaves. A tree with D=kD = k has at least 2k−12^{k-1} leaves, by induction: either one subtree already has D=kD = k, or both subtrees have D=k−1D = k - 1 and so at least 2k−22^{k-2} leaves each.

Predict before you look

A complete binary expression tree has 16 leaves: every operator has two subtrees of the same size. What is the least stack depth that evaluates it?

Show the answer

5

Two equally deep operands always add one level: D=1D = 1 at the leaves, then 2, 3, 4, and 5 at the root, so D=log⁡216+1=5D = \log_2 16 + 1 = 5. Complete trees meet the bound ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 exactly; no choice of order helps, because both operands are always equally deep.

Register allocation is the same problem with registers in place of stack slots. Ershov's numbers (1958) count the registers an expression needs, and Sethi and Ullman (1970) proved that generating code in this order is optimal on a machine with NN registers, spilling values to memory only where DD exceeds NN. In hydrology the same numbers, under the name Strahler numbers, measure the branching of river networks.

What one stack can and cannot do

Why is a stack the right tool? A finite automaton, a machine with a fixed amount of memory, cannot even check balanced parentheses: after reading kk openers it must remember kk. Add one stack and you get a pushdown automaton, and the languages that nondeterministic pushdown automata accept are exactly the context-free languages, as Chomsky, Evey and Schützenberger showed independently in the early 1960s. Deterministic pushdown automata accept exactly the languages with LR(1) grammars (Knuth, 1965), the theory behind parser generators such as yacc and Bison. Two stacks are already as powerful as a Turing machine: one holds the tape to the left of the head, the other the tape to its right.

General context-free grammars, which may be ambiguous, cost more. The CYK and Earley algorithms parse any grammar in O(n3)O(n^3) time. Valiant (1975) reduced recognition to Boolean matrix multiplication, giving O(nω)O(n^{\omega}) time, where ω<2.371339\omega < 2.371339 as of 2025 is the matrix multiplication exponent. Lee (2002) proved a converse: a parser running in O(∣G∣ n3−ε)O(|G|\, n^{3 - \varepsilon}) time on grammars GG would multiply m×mm \times m Boolean matrices in O(m3−ε/3)O(m^{3 - \varepsilon/3}) time. And Abboud, Backurs and Vassilevska Williams (2018) showed that beating Valiant's bound, even for one fixed grammar, would give a faster algorithm for finding kk-cliques in graphs. Expression grammars escape all of this: they are deterministic, so shunting-yard, Pratt and LR parsers run in linear time.

Key takeaways

  • Infix, prefix and postfix are the inorder, preorder and postorder walks of an expression tree. A postfix string is well formed exactly when its running rank stays at least 1 and ends at 1, and it then determines its tree uniquely.
  • Dijkstra's shunting-yard algorithm converts infix to postfix in one pass with one operator stack, popping waiting operators that bind at least as tightly (strictly more tightly when the incoming operator is right-associative). Each token is pushed and popped at most once, so it runs in O(n)O(n).
  • Pratt parsing makes the same decisions with binding powers and recursion: the call stack holds the pending operators.
  • On a stack machine, evaluating the deeper operand first needs only the Ershov number of stack slots, at most ⌊log⁡2n⌋+1\lfloor \log_2 n \rfloor + 1 for nn leaves, instead of up to nn.
  • One stack lifts finite automata exactly to the context-free languages. General context-free parsing is tied to Boolean matrix multiplication, while expression grammars parse in linear time.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A shunting-yard implementation pops a waiting operator of equal precedence whatever the associativity of the incoming one. Which expression does it now get wrong?

  1. 8 - 3 - 1
  2. 2 * 3 + 4
  3. ( 1 + 2 ) * 3
  4. 2 ^ 3 ^ 2, with ^ meant to be right-associative
Show the answer

D. 2 ^ 3 ^ 2, with ^ meant to be right-associative

Popping on equality makes every operator left-associative, so 2 ^ 3 ^ 2 becomes 2 3 ^ 2 ^, which is (23)2=64(2^3)^2 = 64 instead of 232=5122^{3^2} = 512. For left-associative operators such as -, popping on equality is exactly right.

Question 2

One incoming token can make shunting-yard pop many operators. Why is the total time still O(n)O(n)?

  1. Each operator is pushed once and popped at most once, so all the pops together number at most nn
  2. There are few precedence levels, so each token causes at most a constant number of pops
  3. Parentheses keep the stack at O(log⁡n)O(\log n) operators
  4. It is not: the worst case is Θ(n2)\Theta(n^2)
Show the answer

A. Each operator is pushed once and popped at most once, so all the pops together number at most nn

This is the aggregate method of amortized analysis: count the work over the whole run rather than per token. The stack can hold Θ(n)\Theta(n) operators, for instance with nested parentheses or a right-associative chain, and a single token can pop them all, but each one only once.

Question 3

Evaluated with the left operand first, a×(b×(c×(d×e)))a \times (b \times (c \times (d \times e))) needs a stack of depth 5. What is the least depth if the machine may evaluate either operand of each operator first?

  1. 5
  2. 3
  3. 2
  4. 1
Show the answer

C. 2

Each operator has a leaf on one side (depth 1) and a deeper subtree on the other. Evaluating the deeper side first, every level needs max⁡(D,1+1)=2\max(D, 1 + 1) = 2: compute d×ed \times e, then multiply by cc, and so on, never holding more than two values.

Question 4

Which statement about recognizing balanced strings over () and [] is true?

  1. With enough states for every length up to some bound, a finite automaton recognizes them, so the language is regular
  2. One stack suffices, and no finite automaton can do it
  3. It needs two stacks, like a Turing machine
  4. It needs Θ(n3)\Theta(n^3) time, like general context-free parsing
Show the answer

B. One stack suffices, and no finite automaton can do it

The language is context-free but not regular: a finite automaton would have to tell (i\texttt{(}^i from (j\texttt{(}^j for every i≠ji \ne j, which needs infinitely many states, while one stack matches the brackets in a single linear pass. The cubic bounds concern general, possibly ambiguous grammars.

Further reading

  • E. W. Dijkstra, "Algol 60 translation: An Algol 60 translator for the X1 and making a translator for Algol 60," report, Stichting Mathematisch Centrum, Amsterdam (1961).
  • V. R. Pratt, "Top down operator precedence," Proceedings of the 1st ACM Symposium on Principles of Programming Languages (1973), 41–51.
  • R. Sethi & J. D. Ullman, "The generation of optimal code for arithmetic expressions," Journal of the ACM 17(4) (1970), 715–728.
  • L. G. Valiant, "General context-free recognition in less than cubic time," Journal of Computer and System Sciences 10(2) (1975), 308–315.
  • A. Abboud, A. Backurs & V. Vassilevska Williams, "If the current clique algorithms are optimal, so is Valiant's parser," SIAM Journal on Computing 47(6) (2018), 2527–2555.