iq.lab
Python starts when a code cell comes near or you run one
hardStackRecursion target 40 min

Basic calculator

You get a string s that holds an arithmetic expression, and you return its value as an int. The expression is made of whole numbers (0 or more, with one digit or several), the operators + and -, the brackets ( and ), and spaces.

  • Brackets are worked out first, as in school arithmetic, and they can nest: in 5 - (1 - (2 + 4)) the 2 + 4 comes first.
  • A - can also stand with nothing on its left, at the very start or right after a (. Then it negates what follows, as in -(3 - 8) or (-2). This is called a unary minus (unary means it works on one value). A + is never used this way.
  • Spaces can sit between any two parts and change nothing.

The expression is always well formed: the brackets match, and two operators never stand side by side.

Do not use eval or any other built-in that works out text as Python. The tests cannot see how you compute the value, so keeping this rule is up to you, as it would be with an interviewer watching.

Example 1
Inputs = "5 - (1 - (2 + 4))"Output10

The inner bracket is 2 + 4 = 6. Then 1 - 6 = -5, and 5 - (-5) = 10.

Example 2
Inputs = "-(3 - 8) + 12"Output17

A unary minus at the start: -(3 - 8) is -(-5) = 5, and 5 + 12 = 17.

Example 3
Inputs = " 6 -4- (-2) "Output4

Spaces can sit anywhere. The minus right after ( is unary, so the bracket is -2, and 6 - 4 - (-2) = 4.

Constraints
  • 1 ≤ len(s) ≤ 3 × 105

  • s holds only digits, +, -, (, ) and spaces, and is a well-formed expression.

  • Brackets nest at most 105 deep.

  • Every number, every value along the way and the answer are between -231 and 231 - 1.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.