Expression evaluation
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Expression evaluation with a stack computes the answer from a postfix formula. Each number is pushed; each operator pops the top two numbers, calculates, and pushes the result. When the formula ends, the single remaining number is the answer.
Practical use cases
- Web app: A discount rule engine at checkout. A shop owner saved a rule like "cart total * 0.9 - 50". At checkout, the app evaluates the stored postfix form with the real cart total. Each rule is a few quick pushes and pops, so applying five rules to every cart adds almost no waiting time.
- Web app: Computed columns in a report page. A reporting screen lets users define a column such as (revenue - cost) / revenue. The page evaluates it for every row with the same stack routine. With 50,000 rows it just repeats a small loop, and users can change the formula without anyone writing new code.
- System: Virtual machines and calculators. Calculators and many virtual machines run on exactly this idea: numbers wait on a stack until an operator needs them. It is simple to build and easy to test, which is why it appears in so many small interpreters and embedded scripting features inside larger products.
The story: The Bill Counter Without a Pen
Raju's cousin Imran worked at a busy sweet shop and had no time for pen and paper. The owner shouted bills as a chain: "five... one... two... add... four... multiply... add... three... subtract!" Imran never wrote anything. He simply used a spike beside the till, the kind used for holding paper slips.
Each time the owner said a number, Imran stuck a slip with that number on the spike. When the owner said an operator like "add", Imran pulled off the top two slips, did the sum in his head, and stuck the answer back on the spike. The spike was a stack of numbers.
There was one careful moment. For "minus", the order matters: the slip pulled first is the right-hand number, and the one pulled second is the left-hand number. "Five, three, minus" means 5 minus 3, which is 2, not -2!
By the end, one slip remained on the spike: the total. That is postfix evaluation: read left to right, push numbers, and let each operator collapse the top two into one. No brackets and no precedence rules are needed, because the order of the tokens already holds the plan.
How to spot this problem, and where you need it
You have a formula already arranged so operators come after their numbers and you need to compute its value correctly, quickly, and for many different input values.
Signs you need it
- Users store formulas or rules that must be evaluated again and again with changing values, such as prices, quantities or marks.
- Your code uses eval() on user text, which is slow and risky, and you want a safe controlled alternative.
- The task says "evaluate the postfix (reverse Polish) expression".
Where to use it in a project
- Pricing, tax, discount and commission rule engines in shops and billing apps.
- User-defined formulas in reports, dashboards and spreadsheet-style pages, evaluated for every row shown.
- Safe formula features in SaaS products that must never run arbitrary code typed by a customer.
The solution
Read the postfix formula from left to right. When you see a number, push it. When you see an operator, pop the top two numbers (the second popped is the left side), apply the operator and push the result. At the end the stack holds one number, the answer. Because only the formula's own symbols are handled, this is also much safer than running user text as code.
Payoff: Before: risky eval() calls and slow repeated parsing. After: each rule is evaluated in a few quick stack steps and cannot run unexpected code.
Explain it like I am 8
You have a pile of number cards. When someone says a number, you put a card on the pile. When someone says "plus", you take the top two cards, add them, and put one new card with the answer back. At the very end only one card is left: the answer!
How it works, step by step
- Start with an empty stack of numbers. Read the postfix tokens from left to right.
- Number: push it.
- Operator: pop the top value as
b(the right side), then pop the next asa(the left side). - Compute
a op band push the result back. - When tokens run out, exactly one value is left on the stack. That is the answer.
The code in four languages
PHP
<?php
// Evaluate a postfix expression whose tokens are separated by spaces.
function evalPostfix(string $expr): int|float {
$stack = [];
foreach (explode(' ', $expr) as $t) {
if (in_array($t, ['+', '-', '*', '/'], true)) {
$b = array_pop($stack); // right side comes off first
$a = array_pop($stack); // then the left side
$stack[] = match ($t) {
'+' => $a + $b,
'-' => $a - $b,
'*' => $a * $b,
'/' => $a / $b,
};
} else {
$stack[] = (int)$t; // a number: just push
}
}
return array_pop($stack); // the single value left
}
echo evalPostfix('5 1 2 + 4 * + 3 -') . PHP_EOL; // 14
echo evalPostfix('2 3 + 4 *') . PHP_EOL; // 20JavaScript
// Evaluate a postfix expression whose tokens are separated by spaces.
function evalPostfix(expr) {
const stack = [];
for (const t of expr.split(' ')) {
if ('+-*/'.includes(t)) {
const b = stack.pop(); // right side comes off first
const a = stack.pop(); // then the left side
if (t === '+') stack.push(a + b);
else if (t === '-') stack.push(a - b);
else if (t === '*') stack.push(a * b);
else stack.push(a / b);
} else {
stack.push(Number(t)); // a number: just push
}
}
return stack.pop(); // the single value left
}
console.log(evalPostfix('5 1 2 + 4 * + 3 -')); // 14
console.log(evalPostfix('2 3 + 4 *')); // 20Java
import java.util.*;
public class Main {
// Evaluate a postfix expression whose tokens are separated by spaces.
static int evalPostfix(String expr) {
Deque<Integer> stack = new ArrayDeque<>();
for (String t : expr.split(" ")) {
if ("+-*/".contains(t)) {
int b = stack.pop(); // right side comes off first
int a = stack.pop(); // then the left side
stack.push(switch (t) {
case "+" -> a + b;
case "-" -> a - b;
case "*" -> a * b;
default -> a / b;
});
} else {
stack.push(Integer.parseInt(t)); // a number: just push
}
}
return stack.pop(); // the single value left
}
public static void main(String[] args) {
System.out.println(evalPostfix("5 1 2 + 4 * + 3 -")); // 14
System.out.println(evalPostfix("2 3 + 4 *")); // 20
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// evalPostfix evaluates a postfix expression whose tokens are separated by spaces.
func evalPostfix(expr string) int {
var stack []int
for _, t := range strings.Split(expr, " ") {
if strings.Contains("+-*/", t) {
b := stack[len(stack)-1] // right side comes off first
a := stack[len(stack)-2] // then the left side
stack = stack[:len(stack)-2]
switch t {
case "+":
stack = append(stack, a+b)
case "-":
stack = append(stack, a-b)
case "*":
stack = append(stack, a*b)
default:
stack = append(stack, a/b)
}
} else {
n, _ := strconv.Atoi(t)
stack = append(stack, n) // a number: just push
}
}
return stack[0] // the single value left
}
func main() {
fmt.Println(evalPostfix("5 1 2 + 4 * + 3 -")) // 14
fmt.Println(evalPostfix("2 3 + 4 *")) // 20
}Time: O(n) · Extra space: O(n). Each token is handled once. In the worst case all the numbers wait on the stack before any operator arrives.
Watch out for
- Swapping the operands for - and /. The first value popped is the right side, so compute
a - bwith a as the second pop. - Not checking that two numbers exist before an operator pops. A bad expression like "3 +" causes underflow.
- Forgetting that numbers may have several digits. Split on spaces instead of reading one character at a time.
Quick check
- What is the value of the postfix 2 3 4 * +?
- 14
- 9
- 20
- When the token is an operator, how many numbers do you pop?
- One
- Two
- All of them
- For 8 3 - the evaluator pops 3 first and then 8. What is computed?
- 8 + 3
- 3 - 8
- 8 - 3