FastPrepBasic Calculator
Problem · String

Basic Calculator

Learn this problem
HardAmazon logoAmazonONSITE INTERVIEW
See Amazon hiring insights

Problem statement

Given a valid arithmetic expression s, return its evaluated integer value.

The expression may contain:

  • Non-negative integer literals.
  • The binary operators + and -.
  • Parentheses ( and ).
  • Spaces.
  • Unary + or - where a signed expression is valid.

Integer division is not needed because the expression contains no multiplication or division operators.

Function

calculate(s: String) → int

Examples

Example 1

s = "1 + 1"return = 2

The two operands sum to 2.

Example 2

s = " 2-1 + 2 "return = 3

Evaluate from left to right: 2 - 1 + 2 = 3.

Example 3

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

The first parenthesized group evaluates to 9, and 6 + 8 = 14, for a total of 23.

Constraints

  • 1 <= s.length <= 3 * 10^5
  • s is a valid expression containing digits, +, -, (, ), and spaces.
  • Every intermediate and final result fits in a signed 32-bit integer.

More Amazon problems

drafts saved locally
public int calculate(String s) {
  // write your code here
}
s"1 + 1"
expected2
checking account