LeetCode 224: Basic Calculator — Python Solution

LeetCode 224: Basic Calculator is a Hard stack problem. This Python walkthrough develops a sign-context stack solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

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

Recognizing the pattern

A stack is appropriate when the newest unresolved item must be handled before older unresolved items.

For this problem specifically, accumulate a number with the current sign. On an opening parenthesis, save the outer result and sign; on closing, combine the completed inner result. The invariant worth writing beside the code is: result is the value of completed terms in the current parenthesis level, with sign describing the next number or group.

Step-by-step algorithm

  1. Identify the input state consumed by calculate(s) and initialize the data required by the sign-context stack pattern.
  2. Accumulate a number with the current sign. On an opening parenthesis, save the outer result and sign; on closing, combine the completed inner result.
  3. After each update, verify the page’s central invariant: result is the value of completed terms in the current parenthesis level, with sign describing the next number or group.
  4. Finish only after the boundary behavior is covered: Spaces are ignored; unary minus and nested parentheses use the same sign mechanism.

Python solution

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

Reading the implementation

The main entry point is calculate(s). The named working state includes result, stack, number, sign; those variables make the sign-context stack state visible instead of hiding it in incidental control flow.

A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, accumulate a number with the current sign. On an opening parenthesis, save the outer result and sign; on closing, combine the completed inner result.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Accumulate a number with the current sign. On an opening parenthesis, save the outer result and sign; on closing, combine the completed inner result. Each update records the current item without invalidating earlier decisions; consequently, result is the value of completed terms in the current parenthesis level, with sign describing the next number or group.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n) time and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Repeated rescanning can find the same dependency without a stack, but it usually hides the nesting invariant and costs more time. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().calculate("(1+(4+5+2)-3)+(6+8)") == 23

Common mistakes and edge cases

  • Problem-specific boundary: Spaces are ignored; unary minus and nested parentheses use the same sign mechanism.
  • Pattern-level pitfall: Check emptiness before reading the top and decide whether an operator, delimiter, or node is consumed before or after the pop.
  • Invariant check: after every update, confirm that result is the value of completed terms in the current parenthesis level, with sign describing the next number or group.

Interview review checklist

  • Explain why sign-context stack matches the structure of this input.
  • State the invariant in one sentence before tracing code: result is the value of completed terms in the current parenthesis level, with sign describing the next number or group.
  • Derive O(n) time and O(n) space from how many times each element or state is visited.
  • Test the boundary explicitly: Spaces are ignored; unary minus and nested parentheses use the same sign mechanism.

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