← Back to DSA Animator
Basic Calculator LC #224 Hard Stack · Parentheses
Problem

Given a string s representing a valid expression with integers, +, -, (, ), and spaces, implement a basic calculator to evaluate it and return the result. No * or / operators.

Example 1
Input: s = "1 + 1"
Output: 2
Example 2
Input: s = " 2-1 + 2 "
Output: 3
Example 3
Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
Explanation: Inner: 1+4+5+2=12, 12−3=9. Outer: 9+6+8=23.
Example 4
Input: s = "2-(5-6)"
Output: 3
Explanation: Inner: 5−6=−1. Outer: 2−(−1)=3.
Constraints: 1 ≤ s.length ≤ 3×10⁵  |  s consists of digits, '+', '-', '(', ')', and spaces. Expression is always valid.
Try Examples
Custom:
Approach
Stack saves (result, sign) before each '(', restores and merges after ')'
Track: result (so far) + num (building) + sign (±1). Flush num on operator or ')'.
Expression
Stack — Saved States
Stack is empty — not inside any parentheses
Nesting Depth
Level:
0
Computation Variables
result
0
num
0
sign
+1
Current Character State
char c
result
0
num
0
sign
+1
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Digit: accumulate multi-digit numbers — num = num*10 + digit
2
+/−: flush result += sign*num, reset num=0, update sign
3
'(': push result and sign onto stack, then reset result=0, sign=+1
4
')': flush num, then pop: result = savedSign × result + savedResult
5
Return: result + sign*num (handles trailing number after last operator)
Time
O(n)
Space
O(n)
Why Stack Works

Parentheses create nested scopes — each ( starts a fresh sub-expression with its own running sum and sign context. The stack is our memory: we save the outer result and the sign that precedes the '(' (which determines how the inner result merges back). When ) closes the scope, we do inner × savedSign + savedResult, perfectly restoring context. Stack depth equals nesting depth — O(n) space in the worst case.