Arithmetic Expression evaluation

Pattern: Expression conversion and evaluation

medium

Use two stacks, numbers and operators. Before pushing an operator, apply every waiting operator of equal or higher precedence (left to right). Brackets stop that popping until their ) arrives. At the end, apply what is left.

The problem

Evaluate an expression with non-negative whole numbers, + - * /, brackets and spaces. Division keeps the whole part, rounding towards zero; * and / come before + and -, and equal ones go left to right. "100 * ( 2 + 12 ) / 14" gives 100.

The guide's own version; the linked page explains the same two-stack method.

Think first

  • When can an operator be applied?
  • Why must an earlier - be applied before a later -?
  • What should brackets do?

Hints

    Brute force, and why it fails

    Convert to postfix first, then evaluate it: two passes, same O(n).

    The key insight

    An operator waits on a stack until something with equal or lower precedence arrives; then its operands are ready on the number stack.

    Dry run

    nums2 3
    ops+

    s = "2 + 3 * 4". Push 2; push +; push 3.

    Step 1 of 3

    The plan

    for each token:
        number: push to nums
        '(':    push to ops
        ')':    apply until '('; pop '('
        op:     while ops top is an op with rank >= rank(op): apply
                push op
    apply everything left; return nums.top
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each token is pushed and popped once.

    Edge cases

    • A single number.
    • Nested brackets.
    • Division that does not divide evenly: 7 / 2 is 3.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int evaluate(String s) {
            Deque<Integer> nums = new ArrayDeque<>();
            Deque<Character> ops = new ArrayDeque<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == ' ') continue;
                if (Character.isDigit(c)) {                 // read a whole number
                    int v = 0;
                    while (i < s.length() && Character.isDigit(s.charAt(i))) v = v * 10 + (s.charAt(i++) - '0');
                    i--;
                    nums.push(v);
                } else if (c == '(') {
                    ops.push(c);
                } else if (c == ')') {
                    while (ops.peek() != '(') apply(nums, ops.pop());   // finish the bracket
                    ops.pop();
                } else {                                    // an operator: first apply any waiting operator of equal or higher rank
                    while (!ops.isEmpty() && ops.peek() != '(' && rank(ops.peek()) >= rank(c)) apply(nums, ops.pop());
                    ops.push(c);
                }
            }
            while (!ops.isEmpty()) apply(nums, ops.pop());
            return nums.pop();
        }
    
        private int rank(char op) {
            return op == '*' || op == '/' ? 2 : 1;
        }
    
        private void apply(Deque<Integer> nums, char op) {
            int b = nums.pop(), a = nums.pop();             // the right operand is on top
            nums.push(op == '+' ? a + b : op == '-' ? a - b : op == '*' ? a * b : a / b);
        }
    }

    C++

    class Solution {
    public:
        int evaluate(string s) {
            stack<long long> nums;
            stack<char> ops;
            for (size_t i = 0; i < s.size(); i++) {
                char c = s[i];
                if (c == ' ') continue;
                if (isdigit(static_cast<unsigned char>(c))) {   // read a whole number
                    long long v = 0;
                    while (i < s.size() && isdigit(static_cast<unsigned char>(s[i]))) v = v * 10 + (s[i++] - '0');
                    i--;
                    nums.push(v);
                } else if (c == '(') {
                    ops.push(c);
                } else if (c == ')') {
                    while (ops.top() != '(') { apply(nums, ops.top()); ops.pop(); }   // finish the bracket
                    ops.pop();
                } else {                                    // apply any waiting operator of equal or higher rank first
                    while (!ops.empty() && ops.top() != '(' && rank(ops.top()) >= rank(c)) { apply(nums, ops.top()); ops.pop(); }
                    ops.push(c);
                }
            }
            while (!ops.empty()) { apply(nums, ops.top()); ops.pop(); }
            return static_cast<int>(nums.top());
        }
    
        int rank(char op) {
            return op == '*' || op == '/' ? 2 : 1;
        }
    
        void apply(stack<long long>& nums, char op) {
            long long b = nums.top(); nums.pop();          // the right operand is on top
            long long a = nums.top(); nums.pop();
            nums.push(op == '+' ? a + b : op == '-' ? a - b : op == '*' ? a * b : a / b);
        }
    };

    Python

    class Solution:
        def evaluate(self, s: str) -> int:
            nums, ops = [], []
            rank = {"+": 1, "-": 1, "*": 2, "/": 2}
    
            def apply(op: str) -> None:
                b, a = nums.pop(), nums.pop()       # the right operand is on top
                if op == "+":
                    nums.append(a + b)
                elif op == "-":
                    nums.append(a - b)
                elif op == "*":
                    nums.append(a * b)
                else:
                    nums.append(int(a / b) if abs(a) < 2**52 else -(-a // b) if (a < 0) != (b < 0) else a // b)   # toward zero
    
            i = 0
            while i < len(s):
                c = s[i]
                if c.isdigit():                     # read a whole number
                    j = i
                    while j < len(s) and s[j].isdigit():
                        j += 1
                    nums.append(int(s[i:j]))
                    i = j
                    continue
                if c == "(":
                    ops.append(c)
                elif c == ")":
                    while ops[-1] != "(":
                        apply(ops.pop())            # finish the bracket
                    ops.pop()
                elif c in rank:                     # apply any waiting operator of equal or higher rank first
                    while ops and ops[-1] != "(" and rank[ops[-1]] >= rank[c]:
                        apply(ops.pop())
                    ops.append(c)
                i += 1
            while ops:
                apply(ops.pop())
            return nums[-1]

    Common mistakes

    • Applying only higher precedence, not equal, so 10 - 2 - 3 becomes 10 - (2 - 3).
    • Reading a multi-digit number as separate digits.
    • Using Python //, which rounds negative results down.

    Similar problems