#224

Basic Calculator

Hard Stack for parentheses and signs

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Evaluate a string expression with integers, + and -, unary minus, parentheses and spaces. No eval allowed.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: evaluate + and - with brackets.

Why this works: keep a running result and a sign. On '(' save them on the stack and start fresh; on ')' combine with the saved values.

Example: "1 - (2 + 3)"

result 1, sign -'(' saves (1, -) → inner 5')' → 1 + (-1 × 5) = -4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting to add the last number after the loop ends.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n) for nested parentheses.
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon