Basic Calculator - Problem
Given a string s representing a valid mathematical expression, implement a basic calculator to evaluate it and return the result.
The expression contains:
- Non-negative integers
- Addition (
+) and subtraction (-) operators - Parentheses
(and)for grouping - Spaces (which should be ignored)
Note: 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
$
Input:
s = "1 + 1"
›
Output:
2
💡 Note:
Simple addition: 1 + 1 = 2
Example 2 — With Parentheses
$
Input:
s = " 2-1 + 2 "
›
Output:
3
💡 Note:
Left to right evaluation: 2 - 1 + 2 = 1 + 2 = 3
Example 3 — Nested Parentheses
$
Input:
s = "(1+(4+5+2)-3)+(6+8)"
›
Output:
23
💡 Note:
Inner parentheses first: (4+5+2)=11, then (1+11-3)=9, finally 9+14=23
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)" are valid)
- There will be no two consecutive operators in the input
- Every number and running calculation will fit in a 32-bit integer
Visualization
Tap to expand
Understanding the Visualization
1
Input
String expression with numbers, +/-, parentheses, spaces
2
Process
Parse and evaluate respecting parentheses precedence
3
Output
Single integer result
Key Takeaway
🎯 Key Insight: Use a stack to save the current state when entering parentheses and restore it when exiting
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code