hardStackMathStack

Basic Calculator

hardTime: O(n)Space: O(n)

Signals to notice

evaluate expression with + - and parenthesesnested expressionsstack for sub-expressions

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.

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.

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.

Stack Pattern