Basic Calculator
Updated
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) → intExamples
Example 1
s = "1 + 1"return = 2The two operands sum to 2.
Example 2
s = " 2-1 + 2 "return = 3Evaluate from left to right: 2 - 1 + 2 = 3.
Example 3
s = "(1+(4+5+2)-3)+(6+8)"return = 23The first parenthesized group evaluates to 9, and 6 + 8 = 14, for a total of 23.
Constraints
1 <= s.length <= 3 * 10^5sis a valid expression containing digits,+,-,(,), and spaces.- Every intermediate and final result fits in a signed 32-bit integer.
More Motive Phone Screen questions
- Group AnagramsPHONE SCREEN · ONSITE INTERVIEW · Seen Jan 2026
- Longest Equal-Zero-One SubarrayPHONE SCREEN · ONSITE INTERVIEW · Seen Jan 2026
- Valid Parenthesis StringPHONE SCREEN · ONSITE INTERVIEW · Seen Jan 2026
- Search in Rotated Sorted ArrayPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2025
- Pair Left and Right Shoes by SizePHONE SCREEN · Seen Jun 2025
- Lowest Common Ancestor in a Binary TreePHONE SCREEN · Seen Apr 2025
- Mark a Queen’s Attack BoardPHONE SCREEN · Seen Feb 2025
- Count Product-Divisible PairsPHONE SCREEN · Seen Sep 2024
- Resolve Variable Equations with Dependency ErrorsPHONE SCREEN · Seen Jun 2024
- Average Values by Binary-Tree LevelPHONE SCREEN · Seen May 2024
Similar questions at other companies
- Basic CalculatorAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Arithmetic Expression EvaluatorMicrosoft · PHONE SCREENMicrosoft interview questions
- Basic CalculatorNavan · PHONE SCREENNavan interview questions
- Remove Parentheses from a Plus-Minus ExpressionOracle · PHONE SCREENOracle interview questions
- Parse a Partial JSON StreamListen Labs · PHONE SCREEN
- Decode StringCompass International Holdings · PHONE SCREENCompass International Holdings interview questions
- Decode StringBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Calculator with ParenthesesGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Parenthesized String CalculatorMeta · PHONE SCREENMeta interview questions
- Flatten JSON With Array IndicesAdobe · PHONE SCREENAdobe interview questions