Skip to content

visual walkthrough

Basic Calculator

HardExpression EvaluationReported at: GoogleMetaAmazon+6

Signs and nested parentheses with a stack; asked at Google and Meta.

Solve on LeetCode

The idea

Without multiplication, an expression is just a running total with signs. Brackets are the only complication: a minus before a bracket flips everything inside.

So when a bracket opens, save the total so far and the sign in front of it. When it closes, combine: saved total + saved sign × (value inside).

Complexity

approachtimespace
Recursion on bracketsO(n²) worst caseO(n)
One pass with a sign stackO(n)O(n)

More walkthroughs