</> MAANG.io
coding interview ยท 101

Foundations

Master coding interviews with comprehensive coverage of data structures, algorithms, and problem-solving techniques. Progress from fundamentals to advanced topics with expertly curated content.

0/255 solved 0% complete

Expression Evaluation

What is this?

When you work out a sum like 2 + 3 * 4, you can't finish 2 + ... until you've handled 3 * 4 first โ€” so you set the addition aside and come back to it. A stack is the perfect scratch pad for that: it holds the pieces of a calculation you can't finish yet, like a pile of sticky notes, and hands them back the moment the missing number arrives. This is exactly how calculators and programming languages add up expressions.

flowchart TD A["Read the next token"] --> B["A number"] A --> C["An operator"] B --> D["Push it on the stack"] C --> E["Pop the operands and combine"] E --> F["Push the result back"]

๐Ÿ’ก Fun fact: Old HP calculators made you type sums "backwards" as 3 4 + instead of 3 + 4. That postfix style needs no parentheses at all, and it is exactly how a stack-based machine evaluates math under the hood.

๐Ÿ”“ The 2 problems in this chapter are free. Sign in with Google or Microsoft to start solving.


Core idea: Evaluating an expression is a stack story. The stack holds operands waiting for an operator, or a paused sub-expression waiting for its ). Whenever you can't finish a computation yet, you push the unfinished part; when the missing piece arrives, you pop and combine.


Why a stack is the natural fit

Arithmetic has deferred work baked in: you can't apply + until you have both operands, and a ( means "set this aside, I'll come back after the matching )." A stack is precisely the structure for "set aside the most recent unfinished thing and resume it later" โ€” which is also why a CPU-less virtual machine evaluates code with an operand stack.

This chapter teaches the two canonical forms:

Flowchart: expression evaluation splits into infix with parentheses (Basic Calculator) and postfix RPN (Evaluate RPN)


The two problems

Basic Calculator โ€” infix with parentheses

Scan left to right keeping a running result, the current_number, and the current sign. A ( pauses the current computation โ€” push (result, sign) onto the stack and start fresh inside the parentheses. A ) finishes the inner value, then pops the saved context and folds it back in.

Basic Calculator stack pausing and resuming around parentheses in "1 + (2 - (3))"

A ( doesn't start a new problem โ€” it pauses your current one. The stack is a hand-rolled call stack. โ†’ O(n) time, O(n) space.

Evaluate Reverse Polish Notation โ€” postfix, the stack machine

In postfix the operator follows its operands, so no parentheses or precedence rules are needed. Push every number; on an operator, pop the top two, apply, push the result. The last value left is the answer.

Evaluate RPN operand stack machine processing ["4","1","+","3","*"] to 15

Mind the order: the first value popped is the right operand (matters for - and /), and division truncates toward zero. This loop is a miniature bytecode interpreter. โ†’ O(n) time, O(n) space.


The cross-cutting skill: what's on the stack?

Problem Stack holds Pop trigger
Basic Calculator paused (result, sign) contexts a ) resumes the outer expression
Evaluate RPN operands awaiting an operator an operator consumes two operands

Both are "defer until you can combine." Infix defers around parentheses; postfix defers operands until their operator shows up. Name what the stack is holding and the code follows.


Common pitfalls

  • Operand order for - and /: b = pop(); a = pop(); a - b.
  • Truncation toward zero for division of negatives โ€” in Python use int(a / b), not a // b.
  • Multi-digit numbers and spaces in the infix scanner โ€” accumulate digits, skip blanks.
  • Sign handling around ( and leading/unary minus in the calculator.

๐Ÿ““ Draw it yourself

  1. Pause & resume. For Basic Calculator, draw the stack each time you hit ( (push the saved result+sign) and ) (pop and fold back). Watch the outer computation freeze and thaw.
  2. The RPN machine. Draw the operand stack as you scan ["5","1","2","+","*"]; circle the two operands an operator pops and the single result it pushes.

Snap photos and embed them with the /host-diagrams skill.


Complexity at a glance

Problem Time Space
Basic Calculator O(n) O(n)
Evaluate RPN O(n) O(n)

Key takeaways

  • The stack holds deferred work โ€” paused sub-expressions (infix) or pending operands (postfix).
  • Parentheses = push/restore context; a ( pauses, a ) resumes โ€” a hand-built call stack.
  • Postfix needs no precedence or parentheses โ€” which is exactly why VMs and calculators use it.
  • Watch operand order and integer truncation โ€” the two most common bugs here.
  • Why this chapter matters: it's the foundation of compilers, interpreters, and stack machines โ€” the clearest place where "stack = deferred computation" pays off.

Order: Basic Calculator (infix + parens) โ†’ Evaluate RPN (the stack machine).

Basic Calculator

Core idea: A ( lets you pause the calculation you were doing and save it on a stack; a ) lets you resume it โ€” so the stack is just your memory of "where was I?"


Problem, rephrased

Imagine you're building the formula engine behind a tiny spreadsheet. A user types a formula into a cell as plain text โ€” something like 8 - (3 + 2) โ€” and your job is to hand back a single number. The only things they're allowed to write are:

  • whole, non-negative numbers (possibly with several digits, like 42),
  • the operators + and -,
  • round brackets ( and ) to group things,
  • and as many spaces as they feel like sprinkling around.

There is no * or / here โ€” just addition, subtraction, and grouping. Your function gets the raw string and must return the integer it evaluates to. The numbers you type are never negative, but the result of a group certainly can be (e.g. 1 - 5).

Input string Returns Why
"42" 42 a lone number
"8 - (3 + 2)" 3 the group is 5, then 8 - 5
"1 - (-2)" n/a invalid โ€” -2 is a typed negative, not allowed
"(1+(4+5+2)-3)+(6+8)" 23 nested groups
"-(3+2)" -5 a leading minus applied to a whole group
" 100 " 100 spaces are noise

(We'll treat a leading or post-( minus like -(3+2) as valid unary negation, because it falls out of the algorithm for free.)


Sign in to continue reading

The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.

Sign in to read the full lesson

Sign in to MAANG.io

Use your Google or Microsoft account โ€” no password to remember.

Continue with Google Continue with Microsoft

Please accept the terms above to continue.