Basic Calculator - Problem

You're building a smart calculator that can evaluate mathematical expressions from strings! Given a string s representing a valid mathematical expression, your task is to implement a basic calculator that can handle:

  • Addition (+) and subtraction (-)
  • Parentheses for grouping operations
  • Spaces that should be ignored

For example, "1 + 1" should return 2, and "(1+(4+5+2)-3)+(6+8)" should return 23.

Important: You cannot use built-in functions like eval() - you need to parse and evaluate the expression yourself!

This is a classic problem that tests your understanding of expression parsing, operator precedence, and data structures like stacks.

Input & Output

example_1.py โ€” Simple Addition
$ Input: s = "1 + 1"
โ€บ Output: 2
๐Ÿ’ก Note: Basic addition with spaces that should be ignored
example_2.py โ€” Subtraction
$ Input: s = " 2-1 + 2 "
โ€บ Output: 3
๐Ÿ’ก Note: Mixed addition and subtraction: 2 - 1 + 2 = 1 + 2 = 3
example_3.py โ€” Nested Parentheses
$ Input: s = "(1+(4+5+2)-3)+(6+8)"
โ€บ Output: 23
๐Ÿ’ก Note: Complex nested expression: inner (4+5+2)=11, then (1+11-3)=9, finally 9+(6+8)=9+14=23

Visualization

Tap to expand
Calculator State MachineSTARTBUILDNUMBERAPPLYOPERATORHANDLEPARENSENDdigit+/-()endExample: (1+2)*3Step 1: '(' โ†’ Push result=0, sign=1 to stackStep 2: '1+2' โ†’ Calculate inner expression = 3Step 3: ')' โ†’ Pop from stack: 0 + 1*3 = 3Step 4: Continue with result = 3Stacksign=1result=0
Understanding the Visualization
1
Initialize
Start with result=0, number=0, sign=1, empty stack
2
Build Numbers
Accumulate digits to form complete numbers
3
Apply Operations
When hitting +/-, add current number to result and update sign
4
Handle Parentheses
Push current state on '(', pop and combine on ')'
Key Takeaway
๐ŸŽฏ Key Insight: The stack acts as a memory device - save your progress when diving into parentheses, restore and combine when coming back out!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยณ)

For each level of parentheses (O(n)), we scan the entire string (O(n)) and create new strings (O(n))

n
2n
โš  Quadratic Growth
Space Complexity
O(nยฒ)

Recursive calls and string creation at each level

n
2n
โš  Quadratic Space

Constraints

  • 1 โ‰ค s.length โ‰ค 3 ร— 105
  • s consists of digits, '+', '-', '(', ')', and ' '
  • s represents a valid expression
  • '+' is not used as a unary operation
  • '-' could be used as a unary operation (i.e., "-1" and "-(2+3)" is valid)
  • There will be no two consecutive operators in the input
  • Every number and running calculation will fit in a signed 32-bit integer
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
38.5K Views
High Frequency
~25 min Avg. Time
1.4K 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