Basic Calculator II — LeetCode 227 Python Solution

MediumStackMathString
Problem
#227
Pattern
Stack
Reading time
4 min

The problem

Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero.

Example

Input
s = "3+2*2"
Output
7

Python solution

Python
class Solution:
    def calculate(self, s: str) -> int:
        v, n = 0, len(s)
        sign = '+'
        stk = []
        for i, c in enumerate(s):
            if c.isdigit():
                v = v * 10 + int(c)
            if i == n - 1 or c in '+-*/':
                match sign:
                    case '+':
                        stk.append(v)
                    case '-':
                        stk.append(-v)
                    case '*':
                        stk.append(stk.pop() * v)
                    case '/':
                        stk.append(int(stk.pop() / v))
                sign = c
                v = 0
        return sum(stk)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the string s auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 227. Basic Calculator II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 227. Basic Calculator II?
LeetCode 227. Basic Calculator II is rated Medium on LeetCode.
What is the time complexity of LeetCode 227. Basic Calculator II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 227. Basic Calculator II?
The Python solution on this page uses O(n), where n is the length of the string s auxiliary space.
What topics does LeetCode 227. Basic Calculator II cover?
LeetCode 227. Basic Calculator II is tagged Stack, Math and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview