Problem 224

Abstract / Summary

Evaluate a string containing numbers and plus minus signs to compute the result without using division or multiplication.

Note

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

Python 0224.py

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

        num    = 0
        sum    = 0
        minus  = False
        negate = [ minus ]
        # 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)
            elif c == "(":
                negate.append(minus)
            elif c == ")":
                negate.pop()
            else: # "+", "-", "?"
                sum += -num if minus else +num
                num  = 0
                minus = (c == "-")
                if negate[-1] == True:
                    minus = not minus

        return sum
27 lines | 853 bytes | submitted September 9, 2023 | GitHub   27% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Math
  • Recursion
  • 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 an arithmetic expression containing the operators + and -, integer operands, and parentheses. It first removes whitespace, appends a sentinel character to guarantee that the last number is folded into the running total, and then walks through the characters exactly once. A small stack records the sign context introduced by each opening parenthesis, allowing the algorithm to correctly propagate negations through nested groups without building an explicit abstract syntax tree.

Key Steps

Preprocessing and Sentinel Insertion

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

All spaces are stripped so that the parser can treat every remaining character as meaningful. Adding a non-operator sentinel (?) forces the final pending number to be added to the cumulative sum when the loop reaches the end of the original input.

Variable Initialization

num    = 0
sum    = 0
minus  = False
negate = [ minus ]

num accumulates the current multi-digit integer. sum holds the running total. minus records whether the next number should be subtracted. negate is a stack (implemented as a Python list) that stores the sign context at each level of parentheses; the initial context reflects the outermost (non-parenthesized) level.

Main Scan Loop

for c in s:
    if c.isnumeric():
        num = 10 * num + int(c)
    elif c == "(":
        negate.append(minus)
    elif c == ")":
        negate.pop()
    else:  # "+", "-", "?"
        sum += -num if minus else +num
        num  = 0
        minus = (c == "-")
        if negate[-1] == True:
            minus = not minus

The loop distinguishes four categories of characters:

  • Digits - they are folded into num using base-10 multiplication, enabling the parser to handle numbers of arbitrary length without additional conversion steps.
  • Opening parenthesis - the current minus flag is pushed onto negate. This captures the sign that should affect the entire sub-expression inside the new pair of parentheses.
  • Closing parenthesis - the most recent sign context is popped, restoring the sign that applies after the closed group.
  • Operators or sentinel - the accumulated num is folded into sum with the appropriate sign. The sign for the next number (minus) is set based on whether the current operator is -. If the surrounding parentheses have introduced a negation (negate[-1] is True), the sign is flipped, correctly handling expressions such as -(a-b).

Final Result

return sum

After the sentinel forces the last addition, sum contains the evaluated integer value of the entire expression.

Edge Cases Handled

The algorithm gracefully processes inputs that contain leading or trailing spaces because all whitespace is removed before parsing. Empty strings become just the sentinel, causing the loop to add zero and return 0. Consecutive operators are not expected by the problem definition, but the sentinel ensures that a trailing number is never omitted. Nested parentheses of any depth are supported: each opening parenthesis pushes the current sign context, and each closing parenthesis restores it, guaranteeing correct sign propagation through arbitrarily deep nesting. Multi-digit numbers are assembled digit by digit, so numbers like 12345 are handled without overflow concerns in Python’s arbitrary-precision integers.

Performance Optimizations

The solution performs a single linear pass over the input string, avoiding any recursive descent or secondary tokenization phases. By using a simple integer accumulator (num) and updating the total (sum) only when an operator or the sentinel is encountered, the code minimizes the number of arithmetic operations. The sign-context stack (negate) grows only with the nesting depth of parentheses, which in typical use cases is far smaller than the length of the expression, keeping auxiliary memory usage low. The sentinel character eliminates the need for a post-loop cleanup step, allowing the loop body to remain uniform for all characters and thus benefiting from branch prediction in modern CPUs.

written by openai gpt

ELI5 - Simplified Explanation

Imagine this computer code is like a little robot helper designed to solve math problems written in a long row. The robot starts by cleaning up the math problem to make sure there are no messy spaces in the way, and it adds a special secret marker at the end so it knows exactly when to stop working.

There are a few helper spots in the robot's memory. One spot keeps track of the number currently being built, one spot keeps track of the total sum, and another spot remembers if it needs to subtract rather than add. The robot walks through every character of the math problem one by one. If it sees a digit like one or five, it turns that into a number and pushes it into the memory spot for the current number.

When the robot finds a plus or a minus sign, it knows the time has come to add the current number it held onto the total sum. After that, it empties its memory spot so it can start building the next number. The robot continues this process, picking up numbers and signs, until it hits that secret marker at the end which tells it that the math problem is all finished and the total is ready.

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 = 6 | μ = 5.15 | σ = 1.88

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++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java C# Python Go TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
martianoff Scala
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, TypeScript
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
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
martianoff Scala
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
49 links | 34 authors | 11 languages

Videos

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

Similar Problems

7 similar problems

Solved On The Same Day

1 easy 4 medium
6 solutions   September 9, 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