Basic Calculator III - Problem

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only:

  • Non-negative integers
  • '+', '-', '*', '/' operators
  • Open '(' and closing parentheses ')'

Important notes:

  • 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³¹, 2³¹ - 1]
  • You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval()

Input & Output

Example 1 — Basic Expression with Parentheses
$ Input: s = "1 + 1"
Output: 2
💡 Note: Simple addition: 1 + 1 = 2
Example 2 — Complex Expression with All Operations
$ Input: s = "6-4/2"
Output: 4
💡 Note: Following order of operations: 6 - (4/2) = 6 - 2 = 4
Example 3 — Nested Parentheses
$ Input: s = "2*(5+5*2)/3+(6/2+8)"
Output: 21
💡 Note: Step by step: 2*(5+10)/3+(3+8) = 2*15/3+11 = 30/3+11 = 10+11 = 21

Constraints

  • 1 ≤ s.length ≤ 3 × 104
  • 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 of [-231, 231 - 1]
  • You are guaranteed that no division by zero will occur

Visualization

Tap to expand
Basic Calculator III INPUT Expression String: 1 + 1 0 1 2 3 4 Data Structures: Num Stack [values] Op Stack [+,-,*,/] Input: s = "1 + 1" ALGORITHM STEPS 1 Parse Characters Iterate through string, skip whitespace 2 Build Numbers Collect digits into complete numbers 3 Handle Operators Apply precedence: * / before + - 4 Handle Parentheses ( pushes context, ) evaluates inner expr Operator Precedence ( ) Highest * / High + - Low FINAL RESULT Execution Trace: Read '1' --> num=1 Read ' ' --> skip Read '+' --> op='+' Push 1 to numStack Read ' ' --> skip Read '1' --> num=1 End: push 1, eval + Result: 1 + 1 = 2 Output: 2 OK - Valid result Key Insight: Use two stacks: one for numbers and one for operators. When encountering an operator, evaluate all pending operations with higher or equal precedence before pushing the new one. Parentheses act as scope markers - '(' saves state, ')' triggers evaluation of inner expression. TutorialsPoint - Basic Calculator III | Optimal Solution (Two Stack Approach) Time: O(n) | Space: O(n) where n = length of expression
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 25
78.0K Views
High Frequency
~35 min Avg. Time
892 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