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 Navan interview questions
- Roman to IntegerPHONE SCREEN · Seen Oct 2024
- Sort ColorsPHONE SCREEN · Seen Oct 2024
- LRU CachePHONE SCREEN · Seen Jun 2024
- House RobberPHONE SCREEN · Seen May 2024
- House Robber IIPHONE SCREEN · Seen May 2024
- Snake-Case Iterator to Camel CasePHONE SCREEN · Seen Feb 2024
- Lexicographically Largest Distinct-Letter SubsequencePHONE SCREEN · Seen May 2023
- Time Based Key-Value StoreONSITE INTERVIEW · Seen Dec 2025
- Type-Ahead Prefix MatchesONSITE INTERVIEW · Seen Dec 2024
- Minimum Steps on a Circular Character DialONSITE INTERVIEW · Seen Jan 2024
Similar questions at other companies
- Basic CalculatorAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Arithmetic Expression EvaluatorMicrosoft · PHONE SCREENMicrosoft interview questions
- Basic CalculatorMotive · PHONE SCREENMotive 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