3.2 Expression Notations, Operator Precedence & Dijkstra's Shunting-Yard Algorithm
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy: The Railroad Shunting Yardβ
Imagine a train switching yard (a shunting yard) connecting an incoming railroad track to an outgoing departure track:
- Operands () are Express Passenger Trains: They never stop or waitβthey roll straight through the switch directly onto the departure track.
- Operators () are Freight Engines: They wait on a dead-end siding track (the Operator Stack). If a high-speed engine () arrives while a slow engine () sits on the siding, parks ahead of it; when a low-priority engine arrives, buffered higher-priority engines flush onto the departure track first.
- Parentheses (
(and)) are Safety Gates: Holding engines inside the gate until)arrives forces nested groups onto the main track together.
The Railroad Shunting-Yard Mental Model: operands drive straight onto the departure track while operators shunt onto a LIFO siding stack
Infix Tokens (a + b * c)
Mixed operands and operators arrive sequentially left-to-right.
Operator Stack (LIFO)
Delays lower-priority operators until higher-precedence engines clear.
Postfix Output (a b c * +)
Linear, parenthesis-free execution stream emitted in O(n) single pass.
π» Bridging to Computer Science: Why Compilers Reject Infix Notationβ
When humans write arithmetic in Infix Notation (), executing it directly on hardware requires multi-pass bi-directional scanning and arbitrary lookahead ( naive latency). By transforming infix expressions into parenthesis-free Prefix (Polish) or Postfix (Reverse Polish) notation using Dijkstra's Shunting-Yard Algorithm, compilers execute an entire expression deterministically in a single forward sweep.
πTable of Contents
- π The Three Notation Paradigms: Infix, Prefix & Postfix
- βοΈ Operator Precedence & Associativity Grammar
- π Dijkstra's Shunting-Yard Algorithm Engine
- π³ Expression Trees & The Traversal Equivalence Theorem
- π» Industrial C Implementation: The Shunting-Yard Engine
- π Real-World Production Context: Compilers, Calculators & Database Query Parsers
- π Numerical Applications & Worked Examples
- π― Exam & Interview Pitfall Check
- π Navigation & Next Steps
π The Three Notation Paradigms: Infix, Prefix & Postfixβ
An arithmetic expression is computationally optimal for machine execution when:
- Zero Parentheses: Execution order is encoded purely by positional token sequence.
- Single-Pass Determinism: Every operator executes immediately when scanned in time without backtracking.
Every arithmetic expression combines two fundamental lexical categories: Operands (data values or variables) and Operators (mathematical functions mapping operands to results). The position of the operator relative to its operands defines the notation paradigm:
Arithmetic Notation Paradigms: Structural & Computational Comparison
Contrasting human mathematical convention against machine-executable serialized streams
Infix Notation
- β’Operator is placed between operands: A + B.
- β’Requires explicit precedence rules (BODMAS / PEMDAS).
- β’Inherently ambiguous without parentheses: A + B * C vs (A + B) * C.
- β’Requires multi-pass scanning or syntax tree construction for execution.
Postfix (Reverse Polish / RPN)
- β’Operator immediately follows operands: A B +.
- β’Completely parenthesis-free: order of arrival is order of execution.
- β’Evaluated linearly in a single forward pass (Left-to-Right).
- β’Directly mirrors CPU call stacks, JVM bytecode (iadd), and HP calculators.
1. Infix Notation (Human Mathematical Standard)β
- Syntax:
- Example:
- Evaluation Challenge: The computer cannot execute an operator until both operands are resolved. In , the operation must wait because binds more tightly to .
2. Prefix Notation (Polish Notation / Εukasiewicz Notation)β
- Syntax:
- Example:
- Evaluation Direction: Evaluated deterministically from Right to Left using an operand stack. The first operator encountered from the right acts upon the two most recently scanned operands.
3. Postfix Notation (Reverse Polish Notation / Suffix Notation)β
- Syntax:
- Example:
- Evaluation Direction: Evaluated deterministically from Left to Right using an operand stack. Whenever an operator is encountered, it immediately pops the top two operands, executes, and pushes the result back onto the stack.
βοΈ Operator Precedence & Associativity Grammarβ
To convert between notations without altering the semantic meaning of an expression, the parser must strictly adhere to the mathematical precedence and associativity hierarchy.
The Standard Operator Precedence Hierarchyβ
| Operator | Semantic Operation | Precedence Rank | Associativity | In-Stack Precedence (ISP) | Incoming Precedence (ICP) |
|---|---|---|---|---|---|
( ) | Scope Delimiter | Highest (Group) | Left-to-Right | 0 (Lowest inside stack) | Highest (Bypasses all) |
^ or $ | Exponentiation (Power) | 3 (Highest Math) | Right-to-Left | 3 | 4 |
* , / | Multiplication, Division | 2 (Medium Math) | Left-to-Right | 2 | 2 |
+ , - | Addition, Subtraction | 1 (Lowest Math) | Left-to-Right | 1 | 1 |
While standard operators () are Left-to-Right associative, exponentiation () is strictly Right-to-Left associative:
Evaluating from left to right would yield , which is mathematically incorrect! In Shunting-Yard parsing, an incoming ^ does not pop an existing ^ from the stack because right-associative operators bind from right to left.
π Dijkstra's Shunting-Yard Algorithm Engineβ
The Shunting-Yard algorithm processes an infix expression string token by token from left to right. It maintains an Operator Stack to buffer deferred operators and an Output Queue (or stream) that accumulates the resulting postfix expression.
The Formal Algorithmic Rulesβ
For each token in the input string:
- If the token is an Operand (identifier or constant, e.g., ):
- Append it immediately to the output stream.
- If the token is an Opening Parenthesis
(:- Push it onto the Operator Stack. It acts as a barrier preventing earlier operators from popping out of turn.
- If the token is a Closing Parenthesis
):- Continuously pop operators from the Operator Stack and append them to the output stream until the matching
(is at the top of the stack. - Pop and discard the
((it is never written to the output stream).
- Continuously pop operators from the Operator Stack and append them to the output stream until the matching
- If the token is an Operator ():
- While the stack is not empty AND the top of the stack is not
(AND:- , OR
- AND is Left-Associative:
- Pop from the stack and append it to the output stream.
- Push onto the Operator Stack.
- While the stack is not empty AND the top of the stack is not
- End of Input Stream:
- Pop any remaining operators from the Operator Stack one by one and append them to the output stream.
π³ Expression Trees & The Traversal Equivalence Theoremβ
An Expression Tree is a specialized binary tree that models the computational hierarchy of an arithmetic expression:
- Leaf Nodes: Always represent Operands ().
- Internal Nodes: Always represent Operators ().
- Subtrees: Represent grouped sub-expressions whose evaluation produces the operands for their parent operator.
Given a syntactically valid Expression Tree :
- Preorder Traversal generates the Prefix (Polish) Notation.
- Inorder Traversal generates the Infix Notation (recovering original precedence with parenthesization).
- Postorder Traversal generates the Postfix (Reverse Polish) Notation.
Visualizing the Expression Tree for a + b * c - d ^ e ^ fβ
Consider a multi-operator arithmetic expression containing mixed precedence and right-associative exponentiation:
Because exponentiation is right-associative, . Because multiplication precedes addition, binds first. Finally, subtraction connects the two primary branches.
Deriving Traversals from the Treeβ
- Prefix (Preorder Traversal):
- Visit Root, then Left subtree, then Right subtree:
- Postfix (Postorder Traversal):
- Visit Left subtree, then Right subtree, then Root:
- Infix (Inorder Traversal):
- Visit Left subtree, Root, Right subtree (parenthesizing each operation):
π» Industrial C Implementation: The Shunting-Yard Engineβ
Below is the production-grade implementation of Dijkstra's Shunting-Yard algorithm converting an arbitrary infix string into a null-terminated postfix string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_STACK 256
typedef struct {
char items[MAX_STACK];
int top;
} OperatorStack;
void initStack(OperatorStack *s) {
s->top = -1;
}
int isEmpty(OperatorStack *s) {
return s->top == -1;
}
void push(OperatorStack *s, char val) {
if (s->top >= MAX_STACK - 1) {
fprintf(stderr, "Stack Overflow!\n");
exit(EXIT_FAILURE);
}
s->items[++(s->top)] = val;
}
char pop(OperatorStack *s) {
if (isEmpty(s)) {
fprintf(stderr, "Stack Underflow (Mismatched Parentheses)!\n");
exit(EXIT_FAILURE);
}
return s->items[(s->top)--];
}
char peek(OperatorStack *s) {
if (isEmpty(s)) return '\0';
return s->items[s->top];
}
// Operator Precedence Rank: ^ (3), * / (2), + - (1)
int getPrecedence(char op) {
switch (op) {
case '^': return 3;
case '*':
case '/': return 2;
case '+':
case '-': return 1;
default: return 0; // Parentheses or invalid
}
}
// Associativity: ^ is Right-to-Left (returns 1), others are Left-to-Right (returns 0)
int isRightAssociative(char op) {
return (op == '^');
}
void infixToPostfix(const char *infix, char *postfix) {
OperatorStack stack;
initStack(&stack);
int pIdx = 0;
for (int i = 0; infix[i] != '\0'; i++) {
char token = infix[i];
// Skip whitespace
if (isspace(token)) continue;
// 1. If Operand: Emit directly to output stream
if (isalnum(token)) {
postfix[pIdx++] = token;
}
// 2. If Opening Parenthesis: Push unconditionally
else if (token == '(') {
push(&stack, token);
}
// 3. If Closing Parenthesis: Unwind stack until '('
else if (token == ')') {
while (!isEmpty(&stack) && peek(&stack) != '(') {
postfix[pIdx++] = pop(&stack);
}
if (isEmpty(&stack)) {
fprintf(stderr, "Syntax Error: Mismatched parentheses!\n");
exit(EXIT_FAILURE);
}
pop(&stack); // Discard '('
}
// 4. If Operator (+, -, *, /, ^)
else {
int precNew = getPrecedence(token);
while (!isEmpty(&stack) && peek(&stack) != '(') {
char topOp = peek(&stack);
int precTop = getPrecedence(topOp);
// Pop condition: Top has higher precedence OR same precedence with Left-Associativity
if (precTop > precNew || (precTop == precNew && !isRightAssociative(token))) {
postfix[pIdx++] = pop(&stack);
} else {
break;
}
}
push(&stack, token);
}
}
// 5. Unwind remaining operators in stack
while (!isEmpty(&stack)) {
char topOp = pop(&stack);
if (topOp == '(' || topOp == ')') {
fprintf(stderr, "Syntax Error: Mismatched parentheses!\n");
exit(EXIT_FAILURE);
}
postfix[pIdx++] = topOp;
}
postfix[pIdx] = '\0';
}
π Real-World Production Context: Compilers, Calculators & Database Query Parsersβ
The Shunting-Yard algorithm and Polish notations form the backbone of language execution runtimes across computing:
- V8 Engine & Compiler Intermediate Representation (IR):
- When the JavaScript V8 engine parses a mathematical expression like
const x = a + b * c;, the parser converts the lexical AST into Bytecode Instructions. - JVM bytecode and WebAssembly execute zero-address stack instructions:
iload a,iload b,iload c,imul,iadd. This instruction stream is identical to Reverse Polish Notation ().
- When the JavaScript V8 engine parses a mathematical expression like
- Hewlett-Packard (HP) Scientific RPN Calculators:
- Legendary scientific calculators (HP-35, HP-12C, HP-48G) eliminated the
=key entirely. Users enter numbers and operators using Reverse Polish Notation:3 [ENTER] 4 [ENTER] +. - Because RPN requires zero parentheses and zero operator lookahead, HP calculators required minimal RAM and executed operations instantly on low-power microprocessors.
- Legendary scientific calculators (HP-35, HP-12C, HP-48G) eliminated the
- Database Query Planners & Boolean Clause Normalization:
- Relational database engines (PostgreSQL, SQLite) parse SQL
WHEREclauses (e.g.,WHERE age > 18 AND status = 'active' OR role = 'admin') into postfix operator streams to build optimal binary evaluation trees and push down predicate filters.
- Relational database engines (PostgreSQL, SQLite) parse SQL
π Numerical Applications & Worked Examplesβ
Problem 1: Full Step-by-Step Shunting-Yard Trace with Exponentiationβ
Trace Dijkstra's Shunting-Yard algorithm step-by-step to convert the unparenthesized arithmetic expression into Postfix notation:
Step-by-Step Execution Table:β
| Step | Scanned Token | Action Description | Operator Stack (Bottom Top) | Postfix Output Stream |
|---|---|---|---|---|
| 0 | β | Initial state | [ ] | "" |
| 1 | a | Operand Output | [ ] | a |
| 2 | + | Stack empty Push + | [ + ] | a |
| 3 | b | Operand Output | [ + ] | a b |
| 4 | * | Push * | [ +, * ] | a b |
| 5 | c | Operand Output | [ +, * ] | a b c |
| 6 | - | Pop *(Left-Assoc) Pop +Stack empty Push - | [ - ] | a b c * + |
| 7 | d | Operand Output | [ - ] | a b c * + d |
| 8 | ^ | Push ^ | [ -, ^ ] | a b c * + d |
| 9 | e | Operand Output | [ -, ^ ] | a b c * + d e |
| 10 | ^ | , but ^ is Right-Associative Do NOT pop! Push ^ | [ -, ^, ^ ] | a b c * + d e |
| 11 | f | Operand Output | [ -, ^, ^ ] | a b c * + d e f |
| 12 | End | End of input Pop remaining: pop ^, pop ^, pop - | [ ] | a b c * + d e f ^ ^ - |
Final Postfix Output:
Problem 2: Conversion with Nested Parenthesesβ
Convert the following fully parenthesized infix expression into Postfix notation:
Step-by-Step Solution:β
(: Push to stack Stack:[ ( ].A: Operand Output:A.+: Push to stack Stack:[ (, + ].B: Operand Output:A B.): Pop stack until(Pop+to output, discard(Output:A B +, Stack:[ ].*: Stack empty Push*Stack:[ * ].(: Push to stack Stack:[ *, ( ].C: Operand Output:A B + C.-: Stack top is(Push-Stack:[ *, (, - ].(: Push to stack Stack:[ *, (, -, ( ].D: Operand Output:A B + C D.+: Stack top is(Push+Stack:[ *, (, -, (, + ].E: Operand Output:A B + C D E.): Pop until(Pop+Output:A B + C D E +, Stack:[ *, (, - ].): Pop until(Pop-Output:A B + C D E + -, Stack:[ * ].- End of input: Pop remaining Pop
*Output:A B + C D E + - *.
Final Postfix Output:
Problem 3: The Inversion Method for Infix-to-Prefix Conversionβ
Using Dijkstra's Shunting-Yard engine, convert the infix expression to Prefix notation without manually constructing an expression tree.
Step-by-Step Inversion Algorithm:β
- Step 1: Reverse the Infix String:
(Note: If the expression had brackets, reverse each
(to)and vice versa). - Step 2: Modify Associativity & Precedence: In the reversed string, treat Left-Associative operators as Right-Associative to preserve original relative binding.
- Step 3: Run Standard Shunting-Yard to Postfix:
- Scan Output:
C - Scan Push
*(Stack:[*]) - Scan Output:
C B - Scan Pop
*, push+(Output:C B *, Stack:[+]) - Scan Output:
C B * A - Flush stack Pop
+Intermediate Postfix:C B * A +
- Scan Output:
- Step 4: Reverse the Output String:
π― Exam & Interview Pitfall Checkβ
Question 1: "Why does exponentiation (^) remain pushed when another ^ is already at the top of the Operator Stack, whereas + pops an existing +?"
Key Focus Points:
- Left-to-Right Associativity (
+,-,*,/): Equal-precedence operators bind from left to right (), so the earlier operator on the stack must pop and execute before the new operator is pushed. - Right-to-Left Associativity (
^): Exponentiation binds from right to left (), so the incoming operator must evaluate first and therefore sits above the older^on the stack.
Question 2: "How do Expression Tree traversals mathematically unify Infix, Prefix, and Postfix notations?"
Key Focus Points:
- Direct Traversal Correspondence: For a valid binary Expression Tree, Preorder traversal yields Prefix (Polish), Postorder traversal yields Postfix (Reverse Polish), and parenthesized Inorder traversal reconstructs original Infix syntax.
- Operand Order Invariance: Notice that across Infix (), Prefix (), and Postfix (), the relative left-to-right sequence of operands never changesβonly operator positions reorder.
Trap 1: Popping Equal-Precedence Exponentiation (a ^ b ^ c)
Answer: Exponentiation is strictly Right-to-Left associative. Treating ^ as Left-Associative produces instead of the mathematically valid .
Trap 2: Emitting Parentheses Into Postfix or Prefix Output
Answer: Parentheses must NEVER appear in Polish or Reverse Polish notation. Brackets act solely as temporary lexical scope fences inside the Operator Stack; ) pops operators until ( is popped and immediately discarded.
Trap 3: Conflating Binary Minus with Unary Negation (-A + B)
Answer: Lexical disambiguation is mandatory before Shunting-Yard parsing. Binary - consumes two operands at lowest precedence, whereas unary negation consumes one right-hand operand at higher precedence than multiplication and must be tagged as a distinct token (e.g. NEG).
π Navigation & Next Stepsβ
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.