MediumNo. 0227

Basic Calculator II — LeetCode 227 Python Solution

Pattern
Stack
Topics
Stack, Math, String
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)where n is the length of the string s

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

Related problems
No.ProblemDifficulty
0224Basic CalculatorHard
0020Valid ParenthesesEasy
0071Simplify PathMedium
0150Evaluate Reverse Polish NotationMedium
0331Verify Preorder Serialization of a Binary TreeMedium
0385Mini ParserMedium

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.

Free to download. Check it runs on your machine, then pick a plan.