Postfix calculator
medium
New here? How this page works
- Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
- Open Break it down. Answer the questions in your own words. This is your plan.
- Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
- Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
- Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
- Press Submit. It runs hidden tests too. Pass them all, and it's solved.
In postfix notation, each operator comes after the two numbers it works on. 3 4 + means 3 + 4. Longer sums need no brackets: 3 4 + 2 * means (3 + 4) × 2 = 14, and 3 4 2 * + means 3 + (4 × 2) = 11.
tokens is a list of numbers and operators, as strings. The operators are +, -, * and /. Return the result.
Division rounds towards zero, dropping any fraction: 7 / 2 is 3, and -7 / 2 is -3. (Math.trunc does exactly this.)
Examples
Example 1
- Input
- tokens = ["3", "4", "+", "2", "*"]
- Output
- 14
3 + 4 = 7, then 7 × 2 = 14.
Example 2
- Input
- tokens = ["3", "4", "2", "*", "+"]
- Output
- 11
4 × 2 = 8, then 3 + 8 = 11.
Example 3
- Input
- tokens = ["9", "2", "-", "3", "/"]
- Output
- 2
9 − 2 = 7, then 7 ÷ 3 = 2.33…, which rounds towards zero to 2.
Rules
tokensis always a valid postfix sum, with between 1 and 100,000 tokens.- Numbers are whole numbers, and can be negative, like
"-3". No division by zero happens. - Every intermediate result stays between -1,000,000,000 and 1,000,000,000.
Words on this page, in plain English (2)Open if any word is new to you
- String
- A piece of text, written between quotes. Each letter in it is a character.
- Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
Answer each question in your own words before you look at ours. Rough notes are fine: the point is to think before you type code. Your answers stay in this browser.
1.What goes in?
Name every input and what it looks like. Can it be empty? Sorted? Negative?
Stuck? Each hint gives a little more away. Try the problem again after each one.
This explains the whole solution.
You will learn the most by trying first, even if you don’t finish. But if this pattern is new to you, reading the walkthrough first is a fine way to learn it.
1. Understand the problem
Normally we write 3 + 4, with the operator in the middle. In postfix, it goes after: 3 4 +. The nice thing is that postfix never needs brackets. (3 + 4) × 2 becomes 3 4 + 2 *, and 3 + (4 × 2) becomes 3 4 2 * +. Old calculators and some programming languages work this way.
The tokens are strings, so "3" must be turned into the number 3.
2. Solve an example by hand
3 4 + 2 *. Read left to right. 3, 4: just numbers, hold on to them. +: add the last two numbers you're holding: 7. Now you're holding just 7. Then 2. *: multiply the last two: 7 × 2 = 14.
An operator always uses the two most recent numbers you're holding, and its result becomes a number you hold. Most recent first: a stack.
3. The slow way
Find the first operator, replace it and the two numbers before it with the result, and repeat until one number is left: 3 4 + 2 * → 7 2 * → 14. It works, but every replacement rebuilds the list, so a long sum takes O(n²) steps.
4. Spot the pattern
Numbers wait until an operator needs them, and the operator takes the newest ones: a stack of numbers.
5. The stack idea
- A number: push it.
- An operator: pop two numbers, apply the operator, push the result.
- At the end, one number is left: the answer.
Numbers wait on a stack for their operator
tokens
numbers (stack, top first)
- empty
function postfixCalculator(tokens) { const numbers = []; for (const token of tokens) { if (token === "+" || token === "-" || token === "*" || token === "/") { const right = numbers.pop(); // the newest number is the right side const left = numbers.pop(); numbers.push(calculate(left, token, right)); } else { numbers.push(Number(token)); } } return numbers.pop();} function calculate(left, operator, right) { if (operator === "+") return left + right; if (operator === "-") return left - right; if (operator === "*") return left * right; return Math.trunc(left / right); // drop any fraction}An empty stack of numbers.
Order matters for - and /. In 10 2 -, 10 was pushed first, so it's deeper in the stack. The first pop gives 2, the right side; the second gives 10, the left side. Then it's 10 - 2, not 2 - 10.
6. The code, line by line
const numbers = [];The stack of numbers waiting to be used.
for (const token of tokens) { if (token === "+" || token === "-" || token === "*" || token === "/") { const right = numbers.pop(); // the newest number is the right side const left = numbers.pop(); numbers.push(calculate(left, token, right));For an operator, pop the right side first (it's newest), then the left. Work out the result and push it: it can be used by a later operator.
} else { numbers.push(Number(token)); }Anything else is a number.
Number("-3")turns the text into the number -3.return numbers.pop();For a valid sum, exactly one number is left: the answer.
function calculate(left, operator, right) { if (operator === "+") return left + right; if (operator === "-") return left - right; if (operator === "*") return left * right; return Math.trunc(left / right); // drop any fraction}The four operators.
Math.truncdrops the fraction, rounding towards zero: 2.33 becomes 2, and -3.5 becomes -3.
7. How fast is it?
O(n) time: one push or pop per token. O(n) extra memory for the stack in the worst case (many numbers before any operator).
Common mistakes
- Popping in the wrong order.
left - right, whererightis the first pop. - Pushing strings.
"3" + "4"is"34"in JavaScript. Convert withNumber(token). - Using
Math.floorfor division. For negative results it rounds the wrong way:Math.floor(-3.5)is -4, but the answer wants -3.
Memorise the solution, once you understand it.
This shows the full solution, then helps you rebuild it from memory in four steps. Remembering it is what lets you write it again in an interview, or in a week. Your result goes into your reviews, so it comes back just before you'd forget.
Learn it by heart: Postfix calculator
Read the 19 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function postfixCalculator(tokens) { const numbers = []; for (const token of tokens) { if (token === "+" || token === "-" || token === "*" || token === "/") { const right = numbers.pop(); // the newest number is the right side const left = numbers.pop(); numbers.push(calculate(left, token, right)); } else { numbers.push(Number(token)); } } return numbers.pop();} function calculate(left, operator, right) { if (operator === "+") return left + right; if (operator === "-") return left - right; if (operator === "*") return left * right; return Math.trunc(left / right); // drop any fraction}