Basic Calculator — Coding Interview Walkthrough
You’re in a coding interview. The interviewer says: “Implement a basic calculator that evaluates a string expression with +, -, and parentheses.” No multiplication or division, just addition, subtraction, and nested parentheses. This is LeetCode #224, and the challenge is managing sign context through nested parentheses with a stack.
This walkthrough covers the stack-save pattern at ( and ), how to flush pending numbers, and the common parsing traps candidates fall into.
The Problem
Given a string s representing a valid mathematical expression with integers, +, -, (, ), and spaces, evaluate and return the result. The expression is guaranteed to be valid. (LeetCode #224)
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
Already comfortable with the solution? Practice it in a mock interview →
What Interviewers Are Actually Testing
| Skill | What Interviewers Observe |
|---|---|
| Stack for parenthesis context | Do you push (result, sign) onto the stack at each (? |
| Sign tracking | Do you track the current sign and apply it to each number? |
| Multi-digit numbers | Do you build multi-digit numbers character by character? |
| No eval() | Do you implement parsing from scratch? |
| Spaces | Do you skip spaces without breaking number parsing? |
Step 1: Clarifying Questions
1. Can sub-expressions be nested arbitrarily deep? Yes, parentheses can nest to any depth.
2. Are there leading or trailing spaces? Yes, but they should be ignored.
3. Can there be adjacent operators like -- or +-?
No, the expression is guaranteed valid. No adjacent operators.
Step 2: The Key Insight
When you enter a
(, push the current running result and the current sign onto the stack, then reset. When you exit), pop the saved result and sign, and combine:new_result = popped_result + popped_sign * result. This lets you process nested expressions as independent subproblems.
Step 3: Algorithm
- Track
result,num, andsign(initially 1) as you iterate through the string. - Digit: Build multi-digit numbers:
num = num * 10 + int(ch). +or-: Flush pending number (result += sign * num), resetnum, updatesign.(: Pushresultandsignto stack, reset both.): Flush pending number, thenresult = stack.pop() * result + stack.pop().- End of string: Flush the last pending number.
Python Implementation
def calculate(s: str) -> int:
stack = []
result = 0
num = 0
sign = 1 # +1 or -1
for ch in s:
if ch.isdigit():
num = num * 10 + int(ch)
elif ch in ('+', '-'):
result += sign * num
num = 0
sign = 1 if ch == '+' else -1
elif ch == '(':
# Save current state and reset
stack.append(result)
stack.append(sign)
result = 0
sign = 1
elif ch == ')':
result += sign * num
num = 0
result *= stack.pop() # saved sign before this '('
result += stack.pop() # saved result before this '('
# spaces are skipped implicitly
result += sign * num
return result
Time and Space Complexity
| Time | Space | |
|---|---|---|
| Basic Calculator | O(n) | O(n) |
Single pass through the string. Stack depth equals the nesting depth of parentheses.
Common Interview Mistakes
-
Forgetting to flush
numat each operator. When you see+or-, applysign * numtoresultbefore resettingnum. Don’t wait until the end. -
Not flushing
numat). Similar to the operator case. Before combining with the stack values, apply the last pendingnum. -
Building numbers wrong. Multi-digit numbers require
num = num * 10 + int(ch), not justnum = int(ch). -
Using eval(). Never in an interview. Implement the parser manually.
-
Sign across parentheses. After a
-followed by(, the sign inside the parentheses is negated. Pushingsignbefore the(and multiplying by it after the)handles this correctly.
What a Strong Candidate Sounds Like
“I’ll track a running
result, a pendingnum, and the currentsign. At+or-, I flushnum * signintoresult. At(, I push the currentresultandsignonto the stack and reset. At), I flush the pendingnum, then combine with the stack:result = saved_sign * result + saved_result. Single pass, O(n) time, O(n) stack space.”
Example Interview Dialogue
Interviewer: Walk through (1+(4+5+2)-3)+(6+8).
Candidate: Starting with result=0, sign=1. Hit (: push (0, 1), reset result=0, sign=1. Read 1: num=1. Hit +: flush result=1, sign=1. Hit (: push (1, 1), reset result=0, sign=1. Read 4+5+2: result accumulates to 11. Hit ): pop sign=1, pop saved_result=1. result = 111 + 1 = 12. Hit -: sign=-1. Read 3: result = 12 + (-1)3 = 9. Hit ): pop sign=1, pop saved_result=0. result = 19 + 0 = 9. Hit +: sign=1. Hit (: push (9, 1), reset. Read 6+8 = 14. Hit ): result = 114 + 9 = 23. Final answer: 23.
Related Problems to Practice
- Basic Calculator II (LeetCode #227). Adds
*and/, requiring operator precedence handling. - Evaluate Reverse Polish Notation (LeetCode #150). Stack evaluation of postfix expressions.
- Valid Parentheses (LeetCode #20). Parenthesis matching with a simpler stack.
Practice This in a Mock Interview
Basic Calculator is intimidating on the surface but elegant once you see the stack-save pattern at ( and ). Trace through (1+(4+5+2)-3)+(6+8) by hand before your interview to lock in the mechanics.
Start a mock interview for Basic Calculator on Intervu.
Further reading:
- How to Prepare for a Coding Interview in 2026, the complete roadmap and study plans
- Why LeetCode alone isn’t enough, and what to practice instead
- Practice any LeetCode problem as a live mock interview
- The Grind 75 Pathway, a structured study plan with AI practice links
- Browse all walkthroughs on GitHub, condensed solutions with code