HardNo. 0224

Basic Calculator — LeetCode 224 Python Solution

Pattern
Stack
Topics
Stack, Recursion, Math, String
On study lists
Grind 75 and Top Interview 150
Reading time
5 min

The problem

Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Example

Input
s = "1 + 1"
Output
2

Python solution

PythonSolution
class Solution:
    def calculate(self, s: str) -> int:
        stk = []
        ans, sign = 0, 1
        i, n = 0, len(s)
        while i < n:
            if s[i].isdigit():
                x = 0
                j = i
                while j < n and s[j].isdigit():
                    x = x * 10 + int(s[j])
                    j += 1
                ans += sign * x
                i = j - 1
            elif s[i] == "+":
                sign = 1
            elif s[i] == "-":
                sign = -1
            elif s[i] == "(":
                stk.append(ans)
                stk.append(sign)
                ans, sign = 0, 1
            elif s[i] == ")":
                ans = stk.pop() * ans + stk.pop()
            i += 1
        return ans

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 224. Basic Calculator 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
0227Basic Calculator IIMedium
0394Decode StringMedium
1106Parsing A Boolean ExpressionHard
0234Palindrome Linked ListEasy
0020Valid ParenthesesEasy
0071Simplify PathMedium

Frequently asked questions

How hard is LeetCode 224. Basic Calculator?

LeetCode 224. Basic Calculator is rated Hard on LeetCode.

What is the time complexity of LeetCode 224. Basic Calculator?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 224. Basic Calculator?

The Python solution on this page uses O(n), where n is the length of the string s auxiliary space.

What topics does LeetCode 224. Basic Calculator cover?

LeetCode 224. Basic Calculator is tagged Stack, Recursion, 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.