Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Stack

A calculator for plus, minus and brackets

Hard · Target 25 minutes · Stack· Type asked at

You're given a string s holding a valid expression made of non-negative integers, the operators + and -, brackets and spaces. A minus sign can also be unary, but only at the very start of the expression or immediately after an opening bracket (for example -(2 + 3) or 1 - (-2)). Return the value of the expression without using any built-in function that evaluates strings.

The answer and every intermediate value fit in a 32-bit signed integer.

Examples

InputOutputWhy
s = "1 + 1"2The simplest case, with no brackets at all.
s = "(1+(4+5+2)-3)+(6+8)"23The first bracket is 9 and the second is 14.
s = "- (3 + (4 + 5))"-12A unary minus in front of a bracket negates all of it.

Constraints

  • 1 ≤ s.length ≤ 3 × 10⁵
  • s contains digits, + - ( ) and spaces
  • The expression is valid

Hints

Hint 1

Start without brackets, where I'd keep a running total and the sign of the next number, which is all you need for something like 2 - 1 + 2.

Hint 2

An opening bracket starts a brand new running total, but you'll need the old total and the sign in front of the bracket again once the bracket closes, so think about where to keep them.

Hint 3

If you push the total and the sign at '(' and pop them at ')', the finished bracket's value is just total = savedTotal + savedSign × bracketValue, and nested brackets work automatically because the stack remembers each level.

Where people lose marks

  • Adding each digit to the total separately means 12 gets treated as 1 and then 2, so you'll want to finish building the number before using it.
  • Forgetting to add the last number when the string ends is easy to do if you only add numbers when you meet an operator or a bracket.
  • At a closing bracket people sometimes pop the total and the sign in the opposite order to the one they pushed them in, which quietly gives wrong answers on nested brackets.
  • Treating a space as the end of a number only works if numbers never contain spaces, which they don't here, but I'd still skip spaces explicitly so the code doesn't depend on it.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.