↓Skip to main content
  1. LeetCode/

LeetCode 227: Basic Calculator II

·2 mins· ·
LeetCode Medium Math String Stack
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-13

  • Submissions: Wrong Answer → Accepted

Approach
#

There are no parentheses, only precedence (Stack Template 1). Keep the previous operator in op and accumulate digits into a full number; at the next operator or the end, apply op:

  • +: push num; -: push -num.
  • *, /: combine with the stack top and put it back, with division truncating toward zero (int(a / b)).

Sum the stack at the end. Multiplication and division happen immediately while addition and subtraction wait, which respects precedence.

My Attempts
#

  • Attempt 1 turned the string into a list of characters, treating each character as a token, so multi-digit numbers split apart: "18" returned something like 1.
  • Attempt 2 tokenized numbers and operators first and passed, but it replaced slices in place with s[i - 1:i + 2] = [result], shifting the rest each time, O(n²); and it divided with //, which matches truncation toward zero only because every number is non-negative.

Solution
#

class Solution:
    def calculate(self, s: str) -> int:
        st, num, op = [], 0, "+"
        for i, c in enumerate(s):
            if c.isdigit():
                num = num * 10 + int(c)
            if c in "+-*/" or i == len(s) - 1:
                if op == "+":
                    st.append(num)
                elif op == "-":
                    st.append(-num)
                elif op == "*":
                    st.append(st.pop() * num)
                else:
                    st.append(int(st.pop() / num))
                op, num = c, 0
        return sum(st)

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Numbers may have several digits; read them fully.
  • Division truncates toward zero: -3 / 2 is -1, while // gives -2.
  • Handle the last number at the end of the string.

Interview Explanation
#

I remember the previous operator and read numbers fully; at the next operator or the end, + and - push the number (negated for -) while * and / combine with the top, then I sum the stack, which respects precedence. Time O(n).

Related

LeetCode 71: Simplify Path
·2 mins
LeetCode Medium String Stack
LeetCode 71 note: split on /, skip empty pieces and ., pop on .. (never above root), push other names, and join with /
LeetCode 43: Multiply Strings
·2 mins
LeetCode Medium Math String Simulation
LeetCode 43 note: num1[i] × num2[j] lands at position i + j + 1; accumulate into an array of length n + m and carry at the end
LeetCode 151: Reverse Words in a String
·1 min
LeetCode Medium Two-Pointers String
LeetCode 151 note: split() with no argument treats runs of spaces as one separator and drops leading and trailing spaces; reverse and join with single spaces
LeetCode 189: Rotate Array
·2 mins
LeetCode Medium Array Math Two-Pointers
LeetCode 189 note: take k %= n, then reverse three times: the whole array, the first k, and the last n - k, with O(1) extra space
LeetCode 204: Count Primes
·2 mins
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 note: the sieve of Eratosthenes, crossing out multiples of each prime p starting at p², with the outer loop only up to √n
LeetCode 93: Restore IP Addresses
·2 mins
LeetCode Medium String Backtracking
LeetCode 93 note: cut into exactly 4 pieces, each 1 to 3 digits long, valued 0 to 255, with no leading zero except 0 itself