loading

Basic Calculator — Step-by-Step Visualization

hardLeetCode #224MathStringStackRecursion

Given a string s representing a valid expression, implement a basic calculator to evaluate it. The expression may contain digits, '+', '-', '(', ')' and spaces.

Algorithm Pattern

Stack + Sign Tracking

Key Idea

When encountering '(', save current state. On ')', restore and apply saved sign.

Step-by-Step Approach

  1. Track current number, running result, and sign
  2. On '(': push (result, sign), reset to fresh context
  3. On ')': finalize number, pop saved context, combine with saved sign
  4. Apply sign before each number

Common Gotchas

  • Multi-digit numbers must be accumulated before applying to result.
  • At ')' you must finalize the current number before popping.
  • The sign before a '(' applies to the entire sub-expression inside.

Related Problems