Basic Calculator
Problem
Implement a function that evaluates an arithmetic expression given as a string and returns its integer value. The expression contains non-negative integers, the operators + and -, parentheses ( and ), and spaces. A - may appear directly after ( or at the very start, meaning unary negation. You may not use any built-in expression evaluator such as eval.
- The string has between 1 and 400,000 characters.
- The expression is always valid, and every intermediate value fits in a signed 32-bit integer.
Examples
s = "7 - 12"→-5. Results may be negative.s = " 40 - 8 + 3 "→35. Spaces anywhere are ignored, and- 8 + 3is applied left to right.s = "(9-(2+3+1)+7)-(5-15)"→20. The inner groups evaluate to6and-10, giving(9-6+7) - (-10).s = "-(4 - 11)"→7. A minus in front of a parenthesised group flips the sign of everything inside.
Hints
- With only
+and-, you can keep a running total and a "current sign". What breaks that when you hit a(? - Whatever you had accumulated before the
(must be paused and resumed at the matching). Paused state that resumes in reverse order lives on a stack. - Push
(result, sign)on(, reset, and on)pop and combine:result = saved_result + saved_sign * inner_result.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Sign in with your email — no purchase — and this question opens in full, along with 12 others.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395