hardStackMathStack

Basic Calculator

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

Recognize the pattern

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

Brute force idea

If you approach Basic Calculator in the most literal way possible, you get this: 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.

Better approach

The deeper shift in Basic Calculator is this: 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.

Key invariant

At the center of Basic Calculator is one steady idea: 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.

Watch out for

A common way to get lost in Basic Calculator is this: 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