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
Basic Calculator - Stack Approach INPUT Expression String: 1 + 1 0 1 2 3 4 s = "1 + 1" Data Structures Used: stack[] result sign No eval() allowed ALGORITHM STEPS 1 Initialize result=0, sign=1, stack=[] 2 Scan Characters Process each char in string 3 Handle Each Type digit/+/-/(/) logic 4 Return Result Final calculated value Processing "1 + 1": '1': result=0+1*1=1 ' ': skip space '+': sign=1 '1': result=1+1*1=2 FINAL RESULT Calculation Complete: 2 Output: 2 Verification: 1 + 1 = 2 [OK] Time: O(n) Space: O(n) Key Insight: Use a stack to handle parentheses by saving the current result and sign before entering a nested expression. When closing parenthesis is found, pop and combine with outer result. For simple expressions without parentheses, just track cumulative result and current sign. TutorialsPoint - Basic Calculator | Optimal Solution (Stack-based Approach)
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
67.0K Views
High Frequency
~25 min Avg. Time
2.1K 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