> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Basic Calculator III Python Solution

> Tested Python solution for LeetCode 772 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 772, [Hard](/catalog/hard). Topics: [String](/catalog/topics/string), [Stack](/catalog/topics/stack), [Recursion](/catalog/topics/recursion). [View on LeetCode](https://leetcode.com/problems/basic-calculator-iii/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 772   # by problem number
lcpy gen -s basic_calculator_iii   # by problem name
```

## 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 `')'`. The integer division should **truncate toward zero**.

You may assume that the given expression is always valid. All intermediate results will be in the range of `[-2^31, 2^31 - 1]`.

**Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`.

### Examples

```
Input: s = "1+1"
Output: 2
```

```
Input: s = "6-4/2"
Output: 4
```

```
Input: s = "2*(5+5*2)/3+(6/2+8)"
Output: 21
```

### Constraints

* 1 \<= s.length \<= 10^4
* s consists of digits, '+', '-', '\*', '/', '(', and ')'.
* s is a valid expression.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/basic_calculator_iii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/basic_calculator_iii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(n)
    def calculate(self, s: str) -> int:
        def dfs(i: int) -> tuple[int, int]:
            stk: list[int] = []
            num = 0
            sign = "+"
            while i < len(s):
                c = s[i]
                if c.isdigit():
                    num = num * 10 + int(c)
                elif c == "(":
                    num, i = dfs(i + 1)
                if c in "+-*/)" or i == len(s) - 1:
                    if sign == "+":
                        stk.append(num)
                    elif sign == "-":
                        stk.append(-num)
                    elif sign == "*":
                        stk.append(stk.pop() * num)
                    else:
                        stk.append(int(stk.pop() / num))
                    num = 0
                    sign = c
                if c == ")":
                    return sum(stk), i
                i += 1
            return sum(stk), i

        return dfs(0)[0]
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.