Evaluation of Postfix expression

Pattern: Expression conversion and evaluation

medium

Read tokens left to right. Push numbers; for an operator, pop the right operand, then the left one, apply, and push the result. The number left on the stack is the answer.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Evaluate a postfix expression whose tokens are separated by spaces. Numbers may be negative or have several digits; operators are + - * /, and division rounds towards zero. "2 3 1 * + 9 -" gives -4.

The catalogue has no practice link for this one; LeetCode's Evaluate Reverse Polish Notation is the same task with a token array.

Think first

  • When an operator arrives, where are its operands?
  • Which popped number is on the right?
  • Why are no brackets needed?

Hints

    Brute force, and why it fails

    Repeatedly find the first operator, replace it and its two operands with the result: O(n²).

    The key insight

    In postfix every operator follows its operands, so a stack always has them ready on top.

    Dry run

    stack2 3 1

    "2 3 1 * + 9 -". Push 2, 3, 1.

    Step 1 of 3

    The plan

    for tok in s.split():
        if tok is an operator: b = pop; a = pop; push a op b
        else: push int(tok)
    return pop
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each token is handled once.

    Edge cases

    • A single number.
    • Negative numbers such as -7 are numbers, not the minus operator.
    • Division of a negative: -7 2 / is -3.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int evaluatePostfix(String s) {
            Deque<Integer> st = new ArrayDeque<>();
            for (String tok : s.trim().split("\\s+")) {
                if (tok.length() == 1 && "+-*/".indexOf(tok.charAt(0)) >= 0) {
                    int b = st.pop(), a = st.pop();     // the right operand was pushed last
                    char op = tok.charAt(0);
                    st.push(op == '+' ? a + b : op == '-' ? a - b : op == '*' ? a * b : a / b);
                } else {
                    st.push(Integer.parseInt(tok));     // a number waits for its operator
                }
            }
            return st.pop();
        }
    }

    C++

    class Solution {
    public:
        int evaluatePostfix(string s) {
            stack<long long> st;
            stringstream in(s);
            string tok;
            while (in >> tok) {
                if (tok.size() == 1 && string("+-*/").find(tok[0]) != string::npos) {
                    long long b = st.top(); st.pop();   // the right operand was pushed last
                    long long a = st.top(); st.pop();
                    char op = tok[0];
                    st.push(op == '+' ? a + b : op == '-' ? a - b : op == '*' ? a * b : a / b);
                } else {
                    st.push(stoll(tok));                // a number waits for its operator
                }
            }
            return static_cast<int>(st.top());
        }
    };

    Python

    class Solution:
        def evaluatePostfix(self, s: str) -> int:
            st = []
            for tok in s.split():
                if tok in ("+", "-", "*", "/"):
                    b, a = st.pop(), st.pop()           # the right operand was pushed last
                    if tok == "+":
                        st.append(a + b)
                    elif tok == "-":
                        st.append(a - b)
                    elif tok == "*":
                        st.append(a * b)
                    else:
                        st.append(int(a / b))           # division rounds towards zero
                else:
                    st.append(int(tok))                 # a number waits for its operator
            return st[-1]

    Common mistakes

    • Computing b - a instead of a - b.
    • Treating -7 as an operator because it starts with -.

    Similar problems