Skip to content
DSA Patterns
Menu
Language
Stack ParsingLC #1503 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Evaluate Reverse Polish Notation

Problem (restated)

Evaluate an arithmetic expression in reverse Polish notation. Tokens are integers or +, -, *, / (truncate toward zero).

Intuition

Postfix: push numbers; on operator pop two, apply, push result.

Approaches

Stack evaluation

Unverified
Time O(n)Space O(n)

Idea. stack of values; op(a,b) with b then a order.

Walkthrough. [“2”,“1”,“+”,“3”,“*”] → ((2+1)*3)=9.

Trade-offs. No precedence parsing needed, RPN is already ordered.

Solution
export function evalRPN(tokens: string[]): number {
  const st: number[] = [];
  for (const t of tokens) {
    if (t === "+" || t === "-" || t === "*" || t === "/") {
      const b = st.pop()!, a = st.pop()!;
      if (t === "+") st.push(a + b);
      else if (t === "-") st.push(a - b);
      else if (t === "*") st.push(a * b);
      else st.push(Math.trunc(a / b));
    } else st.push(Number(t));
  }
  return st[0]!;
}
export function evalRPN(tokens: string[]): number {
  const st: number[] = [];
  for (const t of tokens) {
    if (t === "+" || t === "-" || t === "*" || t === "/") {
      const b = st.pop()!, a = st.pop()!;
      if (t === "+") st.push(a + b);
      else if (t === "-") st.push(a - b);
      else if (t === "*") st.push(a * b);
      else st.push(Math.trunc(a / b));
    } else st.push(Number(t));
  }
  return st[0]!;
}

Template connection

RPN uses a value stack. A number pushes. An operator pops b then a and pushes a op b. Division truncates toward zero. The last value is the answer.

Reflection

  • - and / care about order. a b - is a - b. The second value you pop is the left operand.
  • Division truncates toward zero. Python // on a negative is not the TypeScript or C# truncation.
  • A valid expression leaves one number. A missing operand empties the stack.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Postfix tokens [2, 1, +, 3, *]. Push numbers; an operator pops two, applies, pushes the result.

2
0
1
1
+
2
3
3
*
4
stack
∅
Key:CurrentActive rangeMatchSettled