Skip to content
Problem 224 · LeetCode 224(opens in a new tab)

Basic Calculator

HardMath

You are given a string s holding an arithmetic expression made of non-negative whole numbers, +, -, brackets ( and ), and spaces. Work out its value and return it.

You must do the evaluation yourself: library helpers that evaluate a string as code, such as eval, are off limits. A - may appear as a negation (as in -4 or -(1+2)), but a + always sits between two operands.

Example 1

Input:  s = "7-(2+3)+4"
Output: 6
Why:    7 − 5 + 4
2 more examples and the constraints

Example 2

Input:  s = " 10 - 4 + 3 "
Output: 9
Why:    spaces do not matter; 10 − 4 + 3

Example 3

Input:  s = "-(6 - 9) + 2"
Output: 5
Why:    the leading minus turns −3 into 3

Constraints

  • 1 ≤ length of s ≤ 300,000
  • s contains only digits, +, -, (, ) and spaces, and is a valid expression
  • No two operators are next to each other
  • Every number and every partial result fits in a signed 32-bit integer

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Rewrite the innermost bracketsO(n²)
  2. One pass with a stack of signsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 300,000 charactersVerdict
Rewrite the innermost bracketsO(n²)
Simple, but copies the string per pair
One pass with a stack of signsO(n)
Best; one read of the string

n = length of the string.

Edge cases to test

  • Unary minus. "-(6 - 9) + 2" and "-5" both start with a minus; the sign handles them with no special case.
  • Numbers with several digits. "10 - 4" must read 10, not 1 and 0: grow num digit by digit.
  • Deep nesting. "((((3))))" pushes four entries and pops them all, leaving 3.
  • A bracket at the very end. "1-(2)" ends with ), so num is already 0 when the loop finishes.
  • A single number. "42" has no operators; the final result + sign * num returns it.

Common mistakes

  • Forgetting to add the last number after the loop ends.
  • Applying the sign in front of a bracket to only the first number inside it.
  • Saving only the result at ( and not the sign in front of it, so 7-(2+3) comes out as 12.

How to talk through it

  1. 1Clarify. Only + and −? Can − be unary? Can I rely on the expression being valid?
  2. 2Give the simple version. Evaluate innermost brackets and splice the value back; it works but is O(n²).
  3. 3Notice the structure. Without × and ÷ every number is just added or subtracted. A bracket only needs the outside total and sign saved.
  4. 4Code the stack. Push (result, sign) on (, pop and fold on ). Say what each variable holds.
  5. 5Test out loud. Run a unary minus, multi-digit numbers, deep nesting and a single number.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?