LeetCode 224: Basic Calculator — Python Solution

Solve LeetCode 224: Basic Calculator in Python with a sign-context stack approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyHard
TopicStack
Reusable patternsign-context stack
ComplexityO(n) time and O(n) space

What the problem is testing

Accumulate a number with the current sign. On an opening parenthesis, save the outer result and sign; on closing, combine the completed inner result.

Algorithm

  1. Accumulate a number with the current sign. On an opening parenthesis, save the outer result and sign; on closing, combine the completed inner result.
  2. Maintain this invariant: result is the value of completed terms in the current parenthesis level, with sign describing the next number or group.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def calculate(self, s):
        result, number, sign = 0, 0, 1
        stack = []
        for char in s + "+":
            if char.isdigit():
                number = number * 10 + int(char)
            elif char in "+-":
                result += sign * number
                number = 0
                sign = 1 if char == "+" else -1
            elif char == "(":
                stack.append(result)
                stack.append(sign)
                result, sign = 0, 1
            elif char == ")":
                result += sign * number
                number = 0
                result = stack.pop() * result + stack.pop()
        return result

Why this is correct

The proof follows the maintained state: result is the value of completed terms in the current parenthesis level, with sign describing the next number or group. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(n) time and O(n) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Spaces are ignored; unary minus and nested parentheses use the same sign mechanism.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 150. Evaluate Reverse Polish Notation · Next: 141. Linked List Cycle