Skip to content
Decoder

Basic Calculator

Hard

Problem

Given a string s holding a valid expression, return its value. The expression contains non-negative integers, +, -, parentheses ( and ), and spaces. A - can also be unary (it negates what follows, as in -(2+3) or -5). There is no * or /. Do not use any built-in function that evaluates strings, like eval.

Example 1

Input
s = "1 + 1"
Output
2

Example 2

Input
s = " 2-1 + 2 "
Output
3

Example 3

Input
s = "(1+(4+5+2)-3)+(6+8)"
Output
23

Example 4

Input
s = "-(2+3)"
Output
-5

Constraints

  • 1 <= s.length <= 3 * 10^5
  • s contains digits, +, -, (, ) and spaces.
  • s is a valid expression. + is never unary; - may be.
  • Every number and every intermediate result fits in a 32-bit integer.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.