Information Technology is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Evaluating postfix and prefix expressions

How to evaluate arithmetic expressions written in postfix (Reverse Polish) and prefix (Polish) notation using a stack, with algorithms, proofs, C++ implementations and exam-style examples.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Postfix and prefix notations remove the need for parentheses and operator-precedence rules, making them easy for machines to evaluate. Engineers encounter them in compiler backends, interpreters, calculators, expression-evaluation libraries, and some data-serialization formats where a simple stack-based evaluation is required.

Key ideas

  • Define operator: a symbol performing an operation on one or more operands (for us: +, -, *, /, ^). We assume binary operators unless stated otherwise.
  • Define postfix notation (also called Reverse Polish Notation, RPN): an expression form where each operator follows its operands. Example: A B + means A + B.
  • Define prefix notation (also called Polish Notation): an expression form where each operator precedes its operands. Example: + A B means A + B.
  • Define stack: a Last-In-First-Out (LIFO) abstract data type supporting push, pop and top (peek). We assume a stack implementation with push(x), pop(), top(), empty().

Exact, university-style statement of the evaluation rule (assumptions: operators are binary, tokens are space-separated, operands are numeric):

  1. Postfix evaluation algorithm (assumption: tokens are read left-to-right):

    • For each token from left to right:
      • If the token is an operand, push its numeric value onto the stack.
      • If the token is an operator, pop the top two values from the stack; call the first popped value R (right operand) and the second popped value L (left operand). Compute L operator R and push the result back onto the stack.
    • After processing all tokens, exactly one value must remain on the stack; this is the expression value. If there are fewer than two values when an operator appears, or more than one value remains at the end, the expression is invalid.
  2. Prefix evaluation algorithm (assumption: tokens are read right-to-left):

    • For each token from right to left:
      • If the token is an operand, push its numeric value onto the stack.
      • If the token is an operator, pop the top two values from the stack; call the first popped value A and the second popped value B. Compute A operator B (because scanning was right-to-left A corresponds to the left operand in the original prefix) and push the result back onto the stack.
    • After processing all tokens, exactly one value must remain on the stack; this is the expression value. Same validity checks as for postfix.

Notes and proofs you may be asked for:

  • Why scanning order differs: Postfix writes operands before their operator, so reading left-to-right meets an operator after its operands; Prefix writes operator before operands, so reading right-to-left meets the operator after the operands in reversed order. This ensures when you see an operator during the scan, its operand values are already on the stack.
  • Operator precedence and parentheses are unnecessary because notation already encodes the order of application. This is the core correctness argument: the notation determines evaluation order uniquely.

Diagram you should draw for an exam when asked to show evaluation steps (draw by hand):

  • Draw a vertical stack on the right side of the page labelled "stack (top at top)".
  • Draw tokens processed left-to-right (postfix) or right-to-left (prefix) across the top with arrows indicating current token.
  • After each token, draw the stack contents (top element at top) showing pushes and pops with labels like "push 5", "pop 2 values (L=5, R=3)", "push 5-3=2". Number the steps.

Complexity (short argument): When tokens are scanned once and each token causes O(1) stack operations, time is O(n) and space is O(n) in the worst case (n = number of tokens).

Formulas

  • space = O(n) — worst-case stack size grows with the number of operands; for a valid binary expression, max stack size ≤ number of operands ≤ n. (No SI unit.)
  • stack<T> s; s.push(x); s.pop(); s.top(); s.empty() — C++ syntax to use a stack. T is the element type and x is a value to push.
  • stoi(s), stod(s) — C++ functions to convert a numeric token string s to integer or double (may throw if invalid). Use std::stod for floating point numbers.
  • result = L op R — arithmetic operation where L is left operand, R is right operand, op is + - * / ^ (for power use pow(L, R)).

Worked examples

  1. Manual evaluation (postfix), step-by-step (classic example): Expression (postfix): 5 1 2 + 4 * + 3 - Goal: compute value. Steps (draw a stack as described in the Diagram section):

    1. Read 5 → operand → push 5. Stack: [5]
    2. Read 1 → push 1. Stack: [1 (top), 5]
    3. Read 2 → push 2. Stack: [2, 1, 5]
    4. Read + → pop R=2, L=1 → compute 1+2=3 → push 3. Stack: [3, 5]
    5. Read 4 → push 4. Stack: [4, 3, 5]
    6. Read * → pop R=4, L=3 → compute 3*4=12 → push 12. Stack: [12, 5]
    7. Read + → pop R=12, L=5 → compute 5+12=17 → push 17. Stack: [17]
    8. Read 3 → push 3. Stack: [3, 17]
    9. Read - → pop R=3, L=17 → compute 17-3=14 → push 14. Stack: [14] End: single value 14 remains. Answer: 14.
  2. Manual evaluation (prefix), step-by-step: Expression (prefix): - + 5 * 4 3 2 Goal: compute value. We scan right-to-left: tokens: 2, 3, 4, *, 5, +, -. Steps:

    1. Read 2 → operand → push 2. Stack: [2]
    2. Read 3 → push 3. Stack: [3, 2]
    3. Read 4 → push 4. Stack: [4, 3, 2]
    4. Read * → pop A=4, B=3 → compute 4*3=12 → push 12. Stack: [12, 2]
    5. Read 5 → push 5. Stack: [5, 12, 2]
    6. Read + → pop A=5, B=12 → compute 5+12=17 → push 17. Stack: [17, 2]
    7. Read - → pop A=17, B=2 → compute 17-2=15 → push 15. Stack: [15] End: single value 15 remains. Answer: 15.
  3. C++ program — Evaluate postfix expressions (space-separated tokens, supports multi-digit and negative numbers and operators + - * / ^). Compile with a standards-compliant C++ compiler. Code (postfix_eval.cpp):

    #include <iostream> #include <sstream> #include <stack> #include <string> #include <cmath> #include <stdexcept> using namespace std;

    bool isOperator(const string &t) { return t=="+" || t=="-" || t=="*" || t=="/" || t=="^"; }

    double applyOp(double L, double R, const string &op) { if (op=="+") return L+R; if (op=="-") return L-R; if (op=="") return LR; if (op=="/") return L/R; // no zero-check here; production code should check if (op=="^") return pow(L,R); throw runtime_error("Unknown operator"); }

    int main() { string line; if (!std::getline(cin, line)) return 0; stringstream ss(line); string token; stack<double> st; while (ss >> token) { if (isOperator(token)) { if (st.size() < 2) { cout << "ERROR" << '\n'; return 0; } double R = st.top(); st.pop(); double L = st.top(); st.pop(); st.push(applyOp(L, R, token)); } else { try { st.push(stod(token)); } catch (...) { cout << "ERROR" << '\n'; return 0; } } } if (st.size() != 1) { cout << "ERROR" << '\n'; return 0; } double res = st.top(); if (fabs(res - round(res)) < 1e-9) cout << (long long)llround(res) << '\n'; else cout << res << '\n'; return 0; }

    Sample input (single line): 5 1 2 + 4 * + 3 -

    Exact output: 14

  4. C++ program — Evaluate prefix expressions (space-separated tokens). Compile as usual. Code (prefix_eval.cpp):

    #include <iostream> #include <sstream> #include <vector> #include <stack> #include <string> #include <cmath> #include <stdexcept> using namespace std;

    bool isOperator(const string &t) { return t=="+" || t=="-" || t=="*" || t=="/" || t=="^"; }

    double applyOp(double A, double B, const string &op) { if (op=="+") return A+B; if (op=="-") return A-B; if (op=="") return AB; if (op=="/") return A/B; if (op=="^") return pow(A,B); throw runtime_error("Unknown operator"); }

    int main() { string line; if (!getline(cin, line)) return 0; stringstream ss(line); vector<string> tokens; string token; while (ss >> token) tokens.push_back(token); stack<double> st; for (auto it = tokens.rbegin(); it != tokens.rend(); ++it) { token = *it; if (isOperator(token)) { if (st.size() < 2) { cout << "ERROR" << '\n'; return 0; } double A = st.top(); st.pop(); double B = st.top(); st.pop(); st.push(applyOp(A, B, token)); } else { try { st.push(stod(token)); } catch (...) { cout << "ERROR" << '\n'; return 0; } } } if (st.size() != 1) { cout << "ERROR" << '\n'; return 0; } double res = st.top(); if (fabs(res - round(res)) < 1e-9) cout << (long long)llround(res) << '\n'; else cout << res << '\n'; return 0; }

    Sample input:

      • 5 * 4 3 2

    Exact output: 15

(These programs print ERROR if the expression is invalid. They do not handle spaces inside numbers or unary operators like unary minus attached without space; for that, tokens must be separated by spaces, e.g., -5 3 +.)

Common mistakes

  • Popping operands in the wrong order. For postfix when operator seen, pop R then L and compute L op R. For prefix scanning right-to-left, pop A then B and compute A op B.
  • Assuming operator precedence still matters. In prefix/postfix it does not — the notation fixes order.
  • Forgetting to handle multi-digit numbers: treating each character as a token (that only works if operands are single letters or single digits).
  • Not checking for invalid expressions: fewer than two operands when operator appears, or more than one value left at the end.
  • Division operand order: doing R/L instead of L/R for binary / when popping in postfix.

For your exam

  • Short note: "Algorithm to evaluate postfix expressions." Full marks: list algorithm steps precisely, mention stack operations, show complexity O(n), and discuss validity checks.
  • Derivation/proof: "Why scanning direction differs for prefix vs postfix?" Full marks: show how operand/operator positions force scanning order and include a short example.
  • Numerical: "Evaluate the postfix expression X." Full marks: draw stack snapshots and show each push/pop with values, final value bolded.
  • Program: "Write C/C++ function to evaluate postfix expressions." Full marks: correct, compilable code that handles multi-digit numbers, explanation of tokenization, and sample run.
  • Diagram question: "Show stack state while evaluating..." Full marks: correctly labeled stack diagrams at each step and clear arrows between tokens and stack changes.

Quick check

  1. In which direction do you scan tokens to evaluate a prefix expression? (one word)
  2. When you see an operator in a postfix scan, which operand do you pop first: the left or the right? (one word)
  3. What is the time complexity of evaluating an expression with n tokens using the stack algorithm? (one expression)

Answers: right-to-left, right, O(n)

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?