Problem 227

Abstract / Summary

Evaluate a math expression with numbers and plus minus multiply divide operators and return the result

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0227.py

class Solution:
    def calculate(self, s: str) -> int:
        s = s.replace(" ", "") # discard spaces
        s += "?"               # end-marker

        op   = "+"
        num  = 0
        todo = []
        # no brackets, almost sequential evaluation possible
        # note: * and / have hive precedence than + and -
        for c in s:
            if c.isnumeric():
                num = 10 * num + int(c)
            else:
                if   op == "+":
                    todo.append(+num)
                elif op == "-":
                    todo.append(-num)
                elif op == "*":
                    last = todo.pop()
                    todo.append(last * num)
                elif op == "/":
                    last = todo.pop()
                    div = last // num
                    if div < 0:
                        div = -(abs(last) // abs(num))
                    todo.append(div)
                op  = c
                num = 0

            if c == "?": # done
                return sum(todo)
32 lines | 1062 bytes | submitted September 8, 2023 | GitHub   17% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 47% (2+ million submissions).

Typical patterns to solve this problem:
  • Math
  • Stack
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation evaluates a mathematical expression given as a string containing non-negative integers and the operators +, -, *, and /. It first removes whitespace, appends a sentinel character to simplify termination, and then walks through the characters once, building intermediate results in a list. The final answer is obtained by summing the list. The algorithm respects the usual precedence rules where multiplication and division are performed before addition and subtraction, without using explicit recursion or a stack of operators.

Key Steps

The core of the solution can be divided into three conceptual phases: preprocessing, token processing, and final aggregation.

Preprocessing

s = s.replace(" ", "")   # discard spaces
s += "?"                 # end-marker

All spaces are stripped to guarantee that only meaningful characters remain. Adding a sentinel ? ensures that the last number is processed without requiring a separate post-loop block.

Token Processing Loop

op   = "+"
num  = 0
todo = []
for c in s:
    if c.isnumeric():
        num = 10 * num + int(c)
    else:
        if   op == "+":
            todo.append(+num)
        elif op == "-":
            todo.append(-num)
        elif op == "*":
            last = todo.pop()
            todo.append(last * num)
        elif op == "/":
            last = todo.pop()
            div = last // num
            if div < 0:
                div = -(abs(last) // abs(num))
            todo.append(div)
        op  = c
        num = 0
    if c == "?":  # done
        return sum(todo)

The loop iterates over each character. When a digit is encountered, it contributes to the current number num using base-10 accumulation. Encountering a non-digit triggers the handling of the previously seen operator stored in op. The handling logic distinguishes four cases:

  • For + the positive value of num is appended.
  • For - the negative value of num is appended.
  • For * the most recent entry in todo is removed, multiplied by num, and the product is pushed back.
  • For / the most recent entry is removed, integer-divided by num, and the quotient is pushed back. A correction step ensures that division truncates toward zero, matching the behavior of typical calculators.

After processing, op is updated to the current character and num is reset, preparing for the next number.

Final Aggregation

The sentinel ? causes an immediate return of the sum of all entries in todo. Because multiplication and division have already been folded into the list, the sum operation yields the correct result respecting operator precedence.

Edge Cases Handled

The code gracefully manages several subtle situations:

  • Multi-digit numbers - The accumulation num = 10 * num + int(c) correctly builds numbers of arbitrary length without overflow concerns in Python.
  • Trailing operator - The sentinel ? forces the final pending operation to be applied, eliminating the need for special end-of-string checks.
  • Division of negative numbers - Python’s floor division (//) rounds toward negative infinity. The additional conditional block detects a negative quotient and recomputes the division using absolute values, then re-applies the sign. This reproduces truncation toward zero, which is the expected behavior for integer division in many programming problems.
  • Consecutive operators without spaces - Because the loop processes an operator only after a number has been fully read, sequences like 3+-2 are interpreted correctly: + processes 3, then - becomes the next operator for 2.
  • Empty or whitespace-only input - After stripping spaces, an empty string becomes just the sentinel ?. The loop immediately returns sum([]), which is 0, a sensible default for an empty expression.

Performance Optimizations

The implementation exhibits several efficiency-focused choices:

  • Single pass traversal - By iterating once over the augmented string, the algorithm avoids multiple scans or recursive descent, keeping the runtime proportional to the length of the input.
  • In-place number construction - Accumulating digits into num avoids creating intermediate substring objects, reducing memory churn.
  • Use of a list as a lightweight stack - The todo list serves both as a container for pending addition/subtraction terms and as a stack for the most recent operand needed by * and /. List append and pop operations are amortized O(1), providing fast updates.
  • Early termination with sentinel - The sentinel character eliminates the need for a separate finalization step after the loop, allowing the function to return as soon as the sentinel is encountered.
  • Avoidance of explicit operator precedence tables - By handling multiplication and division immediately when they appear, the code sidesteps the overhead of shunting-yard algorithms or expression trees, while still respecting precedence.

Overall, the solution delivers a concise, linear-time evaluation of arithmetic expressions with correct handling of integer division semantics and minimal auxiliary data structures.

written by openai gpt

ELI5 - Simplified Explanation

Imagine this code is like a little robot chef helping you solve a math puzzle. First, the robot cleans up the puzzle by taking away any empty spaces so it can see the numbers clearly. It puts a special mark at the end to know when it is finished working.

The robot keeps a list to hold pieces of the math problem. It walks through the symbols one by one. When it finds a number, it builds it up digit by digit. Whenever the robot hits a plus or minus or multiplication or division sign, it decides what to do with that number.

If it sees a plus sign, it saves the number in the list to be added later. If it sees a minus sign, it makes the number small and negative before saving it. If the robot sees multiplication or division, it realizes it needs to do some work right away. It takes the last number it saved out of its list, changes it by the new number, and puts the result back in.

Finally, when the robot hits that special mark at the end, it adds everything in its list together to tell you the final answer.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.07 | σ = 1.02

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Go
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
halfrost Go
JoshCrozier JS
linouk23 C++
lkwq007 Python
martianoff Scala
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
halfrost Go
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
martianoff Scala
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
47 links | 33 authors | 12 languages

Videos

15 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 easy 6 medium
8 solutions   September 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality