FrontendInterviews.dev

Loading problem…

103. Basic Calculator - Expression Evaluator

Hard•
Acceptance: 94.44%
•
🔓3/3 Pro unlocks today

You're building a calculator app that needs to evaluate mathematical expressions. The calculator should handle addition, subtraction, parentheses, and spaces, but no multiplication or division.

Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Requirements

1. Basic Functionality

  • Evaluate expressions with + and - operators
  • Handle parentheses for grouping
  • Handle spaces (ignore them)
  • Support negative numbers
  • Return integer result

Example Usage

calculate("1 + 1");
// 2

calculate(" 2-1 + 2 ");
// 3

calculate("(1+(4+5+2)-3)+(6+8)");
// 23

calculate("-2+ 1");
// -1

Real-World Context

This problem models real calculator features:

  • Calculator apps: Evaluate user input expressions
  • Spreadsheet formulas: Parse and evaluate formulas
  • Expression parsers: Build parsers for mathematical expressions
  • Code evaluators: Evaluate mathematical code expressions

Constraints

  • 1 <= s.length <= 3 * 10^5
  • s consists of digits, '+', '-', '(', ')', and ' '
  • s represents a valid expression
  • All intermediate results fit in 32-bit integer
  • No multiplication or division operators