Basic Calculator III — LeetCode 772 Python Solution
- Problem
- #772
- Pattern
- Stack
- Reading time
- 4 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.