FastPrepEvaluate a Flat Expression or Report Invalid Input
Problems/Evaluate a Flat Expression or Report Invalid Input

Evaluate a Flat Expression or Report Invalid Input

Meta logoMeta● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: A Meta MLE phone-screen report asks for a function to evaluate an expression such as 10/2+1*3+5, without parentheses, and says input can be invalid. The author explicitly discusses multiplication and division taking precedence. This practice supplies the omitted grammar, subtraction, truncating integer division, and exact ERROR result. Approximate source match: 76%.

Evaluate a flat arithmetic expression with nonnegative decimal integer operands and binary operators +, -, *, and /. Multiplication and division take precedence over addition and subtraction; operators at the same precedence are evaluated left to right. There are no parentheses or unary signs.

ASCII spaces may appear before, after, or between complete tokens, but not inside a number. Leading zeros are allowed. Divide integers by truncating toward zero. Return the decimal result as a string.

Return the exact string ERROR if the expression is empty or malformed, contains an unsupported character, has an operand larger than 10^6, or divides by zero. Examples of malformed syntax include adjacent operators, a missing operand, an unexpected parenthesis, and two numbers with no operator between them.

Function

evaluateFlatExpression(expression: String) → String

Examples

Example 1

expression = "10/2+1*3+5"return = "13"

Evaluate division and multiplication first: 5 + 3 + 5 = 13.

Example 2

expression = "20-7/2*3"return = "11"

7/2 truncates to 3, then 3*3 = 9, so the result is 11.

Example 3

expression = "1+*2"return = "ERROR"

The addition operator lacks a number on its right, so the syntax is invalid.

Constraints

  • 0 <= expression.length <= 100.
  • Valid operands are decimal integers from 0 through 10^6.
  • For valid arithmetic, every intermediate value and the final result fit a signed 64-bit integer.
  • Only ASCII spaces are allowed as whitespace.

More Meta problems

  • Count Events in Rolling Minute WindowsPHONE SCREEN · Seen Oct 2026
  • Valid Word AbbreviationPHONE SCREEN · Seen Oct 2026
  • Shortest Path in a Binary MatrixPHONE SCREEN · Seen Sep 2026
All Meta interview questionsSee Meta hiring insights
Saved
class Solution {
    public String evaluateFlatExpression(String expression) {
        // Write your code here.
    }
}
Checking account…