mediumStackMathStack

Basic Calculator II

mediumTime: O(n)Space: O(n)

Signals to notice

evaluate +, -, ×, ÷ without parenthesesoperator precedencestack for deferred addition

Brute force first

Not applicable — parsing requires precedence handling.

The key insight

Stack: for + and -, push number (with sign). For × and ÷, pop top, compute, push result. Sum stack at end. O(n).

What must stay true

× and ÷ resolve immediately (high precedence). + and - are deferred (pushed). Final sum = the answer.

Easy way to go wrong

Integer division toward zero — use Math.trunc(), not Math.floor().

Stack Pattern