Problem Statement
Basic Calculator
You are given a string like "1 + 1" or "(1+(4+5+2)-3)+(6+8)". It only contains digits, plus signs, minus signs, parentheses, and spaces. Your job is to read it left to right and return the number it works out to. There is no multiplication or division here, just adding, subtracting, and grouping with parentheses. The tricky part is the parentheses. A minus sign sitting in front of a group, like "-(2+3)", flips the sign of everything inside it. To keep track of where we were before we stepped into a group, we use a stack. A stack is like a pile of plates: you add a plate to the top and you take a plate from the top, so the last thing you put on is the first thing you take off. That fits here because parentheses nest, and the most recent group you opened is the first one you finish. When we hit an open parenthesis, we put the work-so-far on top of the pile. When we hit the matching close parenthesis, we take that work back off and continue.
Signals to notice
Brute force first
No simpler alternative — parsing requires structured handling of precedence and nesting. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.
The key insight
Stack: push result and sign before '(', reset for the sub-expression. On ')': pop sign and previous result, combine. Handle + and - by tracking the current sign. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.
Trace it on s = " 2-1 + 2 "
init: result=0, num=0, sign=1, stack=[] '2' -> digit: num=2 '-' -> result += sign*num = 1*2 = 2; num=0; sign=-1 '1' -> digit: num=1 '+' -> result += sign*num = -1*1 -> result=1; num=0; sign=1 '2' -> digit: num=2 end of string -> return result + sign*num = 1 + 1*2 = 3 answer = 3
What must stay true
Parentheses create nested scopes. The stack saves the outer context (result so far + sign before '(') so the inner expression can be evaluated independently. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.
Shape of the loop
result=0, num=0, sign=1, stack=[]
for ch in s:
if digit: num = num*10 + ch
elif ch in +/-: result += sign*num; num=0; sign = +1/-1
elif ch=='(': push(result); push(sign); result=0; sign=1
elif ch==')': result += sign*num; num=0; result = result*pop() + pop()
return result + sign*numPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Not handling multi-digit numbers — accumulate digits until you hit a non-digit. Also, spaces between numbers and operators must be skipped. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.