FastPrepParenthesized String Calculator

Parenthesized String Calculator

Meta logoMetaMediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Evaluate a valid arithmetic expression containing nonnegative decimal integers, binary + and -, parentheses, and optional spaces.

Return the integer result. Every operator has an operand on both sides, parentheses are balanced, and all intermediate values fit signed 32-bit range.

Function

calculate(expression: String) → int

Examples

Example 1

expression = "1 + (2 - 3) + 10"return = 10

The parenthesized term equals -1.

Example 2

expression = "12-(4+(2-1))"return = 7

The inner expression is 1, so the grouped value is 5.

Example 3

expression = "42"return = 42

A single literal evaluates to itself.

Constraints

  • 1 <= expression.length <= 10^5.
  • The expression grammar is valid and uses only digits, spaces, +, -, (, and ).
  • Operators are binary; unary signs are not present.

More Meta problems

See Meta hiring insights
public int calculate(String expression) {
    // Write your solution here.
}
expression"1 + (2 - 3) + 10"
expected10
Checking account…