AlgoTales · Roadmap

Expression conversion

Intermediate · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Expression conversion rewrites a formula from the usual infix style into postfix. Numbers go straight to the output, while operators wait on a stack until it is their turn, with stronger operators like times allowed to jump ahead of weaker ones like plus.

Practical use cases

  • Web app: A spreadsheet reading =A1+B1*C1. A web spreadsheet must understand a formula typed in a cell. It converts it so that B1*C1 is calculated first and then added to A1. Converting once means recalculating a column of 10,000 rows is quick, because the order of work is already decided.
  • Web app: A filter box with AND, OR and brackets. A job portal lets recruiters type "(php OR laravel) AND mumbai". The page converts this into an order of operations where bracketed parts go first. The same stack technique that handles + and * handles AND and OR, so the result of the search is correct.
  • System: Compilers and interpreters. Every language that lets you write a + b * c has a conversion step like this. The compiler uses a stack to hold operators and decide, by their strength, when each should be placed in the output, so the later stages never need to think about brackets again.

The story: The Railway Gate Keeper

At a small railway crossing, Mira watched the gate keeper manage a busy hour. Cycles and bikes (the operands) were allowed to pass freely. But heavy trucks (the operators) had to wait in a narrow lane beside the gate, and the lane worked like a stack: the truck that arrived last stood at the front.

When a new truck arrived, the keeper compared it with the one at the front. If the waiting truck was more important or equally important, it was waved through first. Only then did the new truck join the lane. A special red flag, the bracket, meant "everything waiting behind this flag can leave once its partner flag shows up".

"That is exactly how to convert 2 + 3 * 4 into postfix!" Kabir exclaimed. Numbers go to the output at once. Operators wait on a stack. A stronger operator (like *) is allowed to sit on top of a weaker one (like +) because it must be done first. A weaker or equal one forces the waiting operators out first.

This neat trick is called the shunting-yard algorithm, named after railway yards where trains are shunted onto side tracks. It turns the human-friendly infix into the machine-friendly postfix in one left-to-right pass.

How to spot this problem, and where you need it

You must take a formula or query with brackets and operators of different strength and turn it into an order the computer can follow with no guessing.

Signs you need it

  • Operators have different priorities, such as times before plus, or AND before OR, and brackets can change the order.
  • Your hand-written parser works for simple input and breaks for nested brackets or mixed operators.
  • The task mentions the "shunting yard" idea, infix to postfix, or operator precedence.

Where to use it in a project

  • Spreadsheet and report-builder formula features in web apps.
  • Advanced search and filter bars with AND, OR, NOT and brackets.
  • Custom scripting or rules features in SaaS products.

The solution

Read the formula left to right. Numbers go directly to the output. An opening bracket goes onto the stack. For an operator, first move to the output any operators on top of the stack that are as strong or stronger, then push it. A closing bracket moves operators to the output until its opening bracket is found. At the end, empty the stack into the output.

Payoff: Before: a parser with endless special cases for brackets. After: one loop of a few lines that gets every formula in the right order.

Explain it like I am 8

Numbers are children who can walk straight out of the room. Operators are grown-ups waiting in a line. A strong grown-up (times) can stand in front of a weaker one (plus). A weaker one must wait until stronger ones have left. At the end, everyone left in the line goes out, one by one.

How it works, step by step

  1. Read the expression left to right, one token at a time. Keep an empty operator stack and an empty output list.
  2. Operand (number or letter): append it to the output.
  3. Opening bracket: push it onto the stack.
  4. Closing bracket: pop operators to the output until you reach the opening bracket, then discard that bracket.
  5. Operator: while the stack top is an operator with higher or equal precedence, pop it to the output. Then push the new operator.
  6. At the end, pop every remaining operator to the output.

The code in four languages

PHP

<?php
// Convert an infix expression (tokens separated by spaces) to postfix.
function toPostfix(string $expr): string {
    $prec = ['+' => 1, '-' => 1, '*' => 2, '/' => 2];
    $out = [];
    $stack = [];

    foreach (explode(' ', $expr) as $t) {
        if (isset($prec[$t])) {
            // pop operators that are as strong or stronger
            while ($stack && end($stack) !== '(' && $prec[end($stack)] >= $prec[$t]) {
                $out[] = array_pop($stack);
            }
            $stack[] = $t;
        } elseif ($t === '(') {
            $stack[] = $t;
        } elseif ($t === ')') {
            while (end($stack) !== '(') {
                $out[] = array_pop($stack);          // empty the bracket
            }
            array_pop($stack);                       // discard the '('
        } else {
            $out[] = $t;                             // operand goes straight out
        }
    }
    while ($stack) {
        $out[] = array_pop($stack);                  // flush the leftovers
    }
    return implode(' ', $out);
}

echo toPostfix('( A + B ) * C - D') . PHP_EOL;       // A B + C * D -
echo toPostfix('A + B * C') . PHP_EOL;               // A B C * +

JavaScript

// Convert an infix expression (tokens separated by spaces) to postfix.
function toPostfix(expr) {
  const prec = { '+': 1, '-': 1, '*': 2, '/': 2 };
  const out = [];
  const stack = [];
  const top = () => stack[stack.length - 1];

  for (const t of expr.split(' ')) {
    if (t in prec) {
      // pop operators that are as strong or stronger
      while (stack.length && top() !== '(' && prec[top()] >= prec[t]) {
        out.push(stack.pop());
      }
      stack.push(t);
    } else if (t === '(') {
      stack.push(t);
    } else if (t === ')') {
      while (top() !== '(') {
        out.push(stack.pop());                       // empty the bracket
      }
      stack.pop();                                   // discard the '('
    } else {
      out.push(t);                                   // operand goes straight out
    }
  }
  while (stack.length) {
    out.push(stack.pop());                           // flush the leftovers
  }
  return out.join(' ');
}

console.log(toPostfix('( A + B ) * C - D'));         // A B + C * D -
console.log(toPostfix('A + B * C'));                 // A B C * +

Java

import java.util.*;

public class Main {
    // Convert an infix expression (tokens separated by spaces) to postfix.
    static String toPostfix(String expr) {
        Map<String, Integer> prec = Map.of("+", 1, "-", 1, "*", 2, "/", 2);
        List<String> out = new ArrayList<>();
        Deque<String> stack = new ArrayDeque<>();

        for (String t : expr.split(" ")) {
            if (prec.containsKey(t)) {
                // pop operators that are as strong or stronger
                while (!stack.isEmpty() && !stack.peek().equals("(") && prec.get(stack.peek()) >= prec.get(t)) {
                    out.add(stack.pop());
                }
                stack.push(t);
            } else if (t.equals("(")) {
                stack.push(t);
            } else if (t.equals(")")) {
                while (!stack.peek().equals("(")) {
                    out.add(stack.pop());                    // empty the bracket
                }
                stack.pop();                                 // discard the '('
            } else {
                out.add(t);                                  // operand goes straight out
            }
        }
        while (!stack.isEmpty()) {
            out.add(stack.pop());                            // flush the leftovers
        }
        return String.join(" ", out);
    }

    public static void main(String[] args) {
        System.out.println(toPostfix("( A + B ) * C - D"));  // A B + C * D -
        System.out.println(toPostfix("A + B * C"));          // A B C * +
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

// toPostfix converts an infix expression (tokens separated by spaces) to postfix.
func toPostfix(expr string) string {
	prec := map[string]int{"+": 1, "-": 1, "*": 2, "/": 2}
	var out []string
	var stack []string
	top := func() string { return stack[len(stack)-1] }
	pop := func() string {
		x := top()
		stack = stack[:len(stack)-1]
		return x
	}

	for _, t := range strings.Split(expr, " ") {
		if _, isOp := prec[t]; isOp {
			// pop operators that are as strong or stronger
			for len(stack) > 0 && top() != "(" && prec[top()] >= prec[t] {
				out = append(out, pop())
			}
			stack = append(stack, t)
		} else if t == "(" {
			stack = append(stack, t)
		} else if t == ")" {
			for top() != "(" {
				out = append(out, pop()) // empty the bracket
			}
			pop() // discard the '('
		} else {
			out = append(out, t) // operand goes straight out
		}
	}
	for len(stack) > 0 {
		out = append(out, pop()) // flush the leftovers
	}
	return strings.Join(out, " ")
}

func main() {
	fmt.Println(toPostfix("( A + B ) * C - D")) // A B + C * D -
	fmt.Println(toPostfix("A + B * C"))         // A B C * +
}

Time: O(n) · Extra space: O(n). Every token is pushed at most once and popped at most once, so one pass is enough.

Watch out for

  • Popping only when the top is strictly stronger. For equal strength (like A - B - C) the earlier operator must go first, so pop on greater or equal.
  • Treating "(" as an operator with a precedence. Stop popping when you reach it; never pop it to the output.
  • Forgetting to flush the stack at the end, so the last operators go missing from the result.

Quick check

  1. What happens to an operand (like A) while converting?
    • It goes straight to the output
    • It is discarded
    • It is pushed on the stack
  2. What does postfix of A + B * C look like?
    • A B + C *
    • A B C * +
    • + A * B C
  3. You read ")" . What do you do?
    • Clear the whole stack and output
    • Push it on the stack
    • Pop operators to the output until "(" appears