Basic Calculator II With Empty Input
Updated
Problem statement
Evaluate an arithmetic expression containing non-negative integers, spaces, and the binary operators +, -, *, and /. Do multiplication and division before addition and subtraction. Within either pair of operations, work from left to right.
After each integer division, discard the fractional part, rounding toward zero. The expression contains no parentheses. If expression is empty or contains only spaces, return 0.
Function
calculate(expression: String) → intExamples
Example 1
expression = "3+2*2"return = 7Multiplication is evaluated first, so the result is 3 + 4 = 7.
Example 2
expression = " 14-3/2 "return = 133 / 2 truncates to 1, giving 14 - 1.
Example 3
expression = " "return = 0A spaces-only expression is the explicit empty case.
Constraints
0 <= expression.length <= 200000.- After spaces are removed, a non-empty expression alternates non-negative base-10 integers and operators from
+,-,*, and/. - No divisor is zero.
- Every intermediate and final result fits a signed 32-bit integer.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Calculate a Token-List ExpressionCollege Vine · ONSITE INTERVIEW
- Basic Calculator IITypeSafe AI · OA
- Basic Calculator IISnap Inc. · PHONE SCREENSnap Inc. interview questions
- Adjacent Equal-Pair Removal GameZipRecruiter · OAZipRecruiter interview questions
- Evaluate Arithmetic with Operator PrecedenceRoblox · PHONE SCREENRoblox interview questions
- Simplify a Formula with Known and Unknown VariablesBetter.com · PHONE SCREEN
- Evaluate Parenthesized Addition and SubtractionAtlassian · PHONE SCREENAtlassian interview questions
- Smallest Value for a Linear Expression ModuloIntel · OA
- Adjacent Pair and Run RemovalWhatNot · PHONE SCREEN · ONSITE INTERVIEWWhatNot interview questions
- Single-Pass S-Expression ParserBaseten · ONSITE INTERVIEWBaseten interview questions