Basic Calculator III - Problem
Build a Mathematical Expression Evaluator

You're tasked with implementing a basic calculator that can evaluate complex mathematical expressions containing:

• Non-negative integers (e.g., 123, 0, 99)
• Basic operators: +, -, *, /
• Parentheses for grouping: ( and )

The calculator must respect operator precedence (multiplication and division before addition and subtraction) and handle nested parentheses. For division, use integer division that truncates toward zero (e.g., 7/3 = 2, -7/3 = -2).

Goal: Parse the expression string and return the calculated result as an integer.

Example: "2*(5+5*2)/3+(6/2+8)" should evaluate to 21

Input & Output

example_1.py — Basic Expression
$ Input: s = "1 + 1"
Output: 2
💡 Note: Simple addition of two numbers gives us 2
example_2.py — Expression with Precedence
$ Input: s = "6-4/2"
Output: 4
💡 Note: Division has higher precedence: 6 - (4/2) = 6 - 2 = 4
example_3.py — Complex with Parentheses
$ Input: s = "2*(5+5*2)/3+(6/2+8)"
Output: 21
💡 Note: Step by step: (5+5*2) = (5+10) = 15, then 2*15/3 = 30/3 = 10. (6/2+8) = (3+8) = 11. Finally: 10+11 = 21

Time & Space Complexity

Time Complexity
⏱️
O(n)

Single pass through the string, each character processed once

n
2n
Linear Growth
Space Complexity
O(n)

Stack space for intermediate numbers and recursion depth for parentheses

n
2n
Linearithmic Space

Constraints

  • 1 ≤ s.length ≤ 3 * 105
  • s consists of integers and operators ('+', '-', '*', '/', '(', ')') separated by some number of spaces
  • s represents a valid expression
  • All intermediate results will be in the range [-231, 231 - 1]
  • Integer division should truncate toward zero
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen