LeetCode 772, Hard. Topics: String, Stack, Recursion. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:
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
Constraints
- 1 <= s.length <= 10^4
- s consists of digits, ’+’, ’-’, ’*’, ’/’, ’(’, and ’)’.
- s is a valid expression.
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026