CodingNodes / Stack / Basic Calculator System design Space play · ←→ step · R restart

Problem

You are given a string s that holds an arithmetic expression. Work out its value and return it as an integer, without using any built-in expression evaluator.

The expression contains non-negative whole numbers, the operators + and -, parentheses, and spaces. A - may also appear with nothing in front of it, meaning "negate what follows", as in -(2+3) or -4. A + is never used that way.

Constraints

  • 1 ≤ s.length ≤ 3 · 10⁵
  • s contains only digits, '+', '-', '(', ')' and spaces
  • s is a valid expression, and every parenthesis is matched
  • Every number and every intermediate value fits in a signed 32-bit integer

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Each character is read once and does O(1) work: a digit update, a sign change, or one push or pop.

Space: The stack holds one (result, sign) pair per open parenthesis, so up to about n / 2 pairs for deeply nested input.

Keep a running result, the sign of the next number, and the number being read. A + or - adds sign × number to the result and sets the new sign. On (, save (result, sign) on a stack and start fresh. On ), finish the inside, pop the pair, and combine: saved result + saved sign × inside.