Basic Calculator III — LeetCode 772 Python Solution

HardLeetCode PremiumStackRecursionMathString
Problem
#772
Pattern
Stack
Reading time
4 min

The problem

Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, '+', '-', '*', '/' operators, and open '(' and closing parentheses ')'.

Example

Input
s = "1+1"
Output
2

Python solution

Python
class Solution:
    def calculate(self, s: str) -> int:
        def dfs(q):
            num, sign, stk = 0, "+", []
            while q:
                c = q.popleft()
                if c.isdigit():
                    num = num * 10 + int(c)
                if c == "(":
                    num = dfs(q)
                if c in "+-*/)" or not q:
                    match sign:
                        case "+":
                            stk.append(num)
                        case "-":
                            stk.append(-num)
                        case "*":
                            stk.append(stk.pop() * num)
                        case "/":
                            stk.append(int(stk.pop() / num))
                    num, sign = 0, c
                if c == ")":
                    break
            return sum(stk)

        return dfs(deque(s))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 772. Basic Calculator III 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 772. Basic Calculator III?
LeetCode 772. Basic Calculator III is rated Hard on LeetCode.
What is the time complexity of LeetCode 772. Basic Calculator III?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 772. Basic Calculator III?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 772. Basic Calculator III cover?
LeetCode 772. Basic Calculator III is tagged Stack, Recursion, Math and String on LeetCode.
Is LeetCode 772. Basic Calculator III a premium problem?
Yes. LeetCode 772. Basic Calculator III is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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