Basic Calculator III

HardStackrecursive descent / stack

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Implement a basic calculator that evaluates a string expression s and returns its integer result. The expression may contain: - Non-negative integers - The four binary operators +, -, *, and / - Matching parentheses ( and ) - Spaces (which should be ignored) The evaluation must respect standard operator precedence: multiplication and division bind tighter than addition and subtraction, and parentheses override precedence by forcing the enclosed sub-expression to be evaluated first. Integer division should **truncate toward zero** (for example, 14 / 3 is 4 and -7 / 2 is -3). You may assume the input is always a valid expression, that every / divisor is non-zero, and that the final answer as well as every intermediate value fits in a signed 32-bit integer. You are not allowed to use any built-in expression-evaluation routine (such as eval).

Examples

Input: s = "1+1"
Output: 2
A single addition of two integers.
Input: s = "6-4/2"
Output: 4
Division binds tighter than subtraction, so this is 6 - (4/2) = 6 - 2 = 4.
Input: s = "2*(5+5*2)/3+(6/2+8)"
Output: 21
The first group is 2*(5+10)/3 = 2*15/3 = 10, and the second group is (3+8) = 11, giving 10 + 11 = 21.

Constraints

  • `1 <= s.length <= 10^4`
  • `s` consists of digits, `+`, `-`, `*`, `/`, `(`, `)`, and space characters
  • `s` is a valid expression with balanced parentheses
  • All integers in `s` are in the range `[0, 2^31 - 1]`
  • No division by zero occurs
  • The answer and all intermediate results fit in a signed 32-bit integer

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.