Basic Calculator II - Problem

๐Ÿงฎ Build Your Own Calculator

You're tasked with creating a mathematical expression evaluator that can handle basic arithmetic operations. Given a string s containing an expression with integers and operators (+, -, *, /), your job is to evaluate it and return the result.

Key Requirements:

  • Handle operator precedence correctly (* and / before + and -)
  • Integer division should truncate toward zero (not floor division)
  • No built-in eval() functions allowed
  • All expressions are guaranteed to be valid

Example: "3+2*2" should return 7 (not 10), because multiplication has higher precedence.

Input & Output

example_1.py โ€” Basic Expression
$ Input: s = "3+2*2"
โ€บ Output: 7
๐Ÿ’ก Note: Multiplication has higher precedence: 3 + (2*2) = 3 + 4 = 7
example_2.py โ€” Division with Truncation
$ Input: s = "3/2"
โ€บ Output: 1
๐Ÿ’ก Note: Integer division truncates toward zero: 3/2 = 1.5 โ†’ 1
example_3.py โ€” Complex Expression
$ Input: s = "3+5/2"
โ€บ Output: 5
๐Ÿ’ก Note: Division first, then addition: 3 + (5/2) = 3 + 2 = 5

Visualization

Tap to expand
๐Ÿงฎ Smart Calculator State MachineSCANBuild NumbersDECIDECheckPrecedenceCOMPUTEHigh Precedence* / ImmediateDEFERLow Precedence+ - To StackNumber Ready* /+ -๐Ÿ“š Example Walkthrough: "3+2*4-1"1. Scan '3': number=3, op='+'2. Hit '+': DEFER โ†’ stack=[3], op='+', number=03. Scan '2': number=2, op='+'4. Hit '*': DEFER โ†’ stack=[3, 2], op='*', number=05. Scan '4': number=4, Hit '-': COMPUTE โ†’ 2*4=8, stack=[3, 8], then DEFER โ†’ stack=[3, 8, -1]๐ŸŽฏ Key Insight: Let the stack handle precedence naturally - immediate compute for *, / and defer for +, -
Understanding the Visualization
1
Scan & Build Numbers
Read digits and build complete numbers while tracking the last operator
2
Decision Point
When encountering an operator, decide: compute now (*, /) or defer (+, -)?
3
Stack Management
High precedence ops modify stack top immediately, low precedence ops add to stack
4
Final Computation
Sum everything in the stack - all precedence has been handled!
Key Takeaway
๐ŸŽฏ Key Insight: The stack approach elegantly solves precedence by making high-precedence operations execute immediately while deferring low-precedence operations. This transforms a complex parsing problem into simple stack operations!

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 can contain at most n/2 numbers in worst case (alternating numbers and + operators)

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 the integers in the expression are non-negative integers in the range [0, 231 - 1]
  • The answer is guaranteed to fit in a 32-bit integer
Asked in
Google 48 Amazon 35 Facebook 28 Microsoft 22 Apple 18
142.4K Views
High Frequency
~25 min Avg. Time
2.8K 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