Smallest Value for a Linear Expression Modulo
Updated
Problem statement
You are given an arithmetic expression in the variable x, a target remainder p, and a modulus m. The expression uses non-negative integer literals, x, binary +, binary -, binary *, and parentheses. Multiplication is always written explicitly, and there are no unary operators.
After ordinary distribution, the complete expression is guaranteed to be a first-degree polynomial in x. A solution is guaranteed to exist. Return the smallest non-negative integer x such that evaluating the expression and dividing by m leaves remainder p.
Function
smallestNonnegativeX(expression: String, p: int, m: int) → intExamples
Example 1
expression = "4+x+2"p = 8m = 9return = 2The expression equals x + 6. Values 0 and 1 leave remainders 6 and 7; x = 2 is the first value that leaves remainder 8.
Example 2
expression = "2*(x+(x+3)*9)"p = 2m = 6return = 1The restored explicit multiplications give 20x + 54. Modulo 6, this is 2x, so the smallest value producing remainder 2 is 1.
Constraints
1 <= expression.length <= 60000.expressionfollows the stated binary-operator grammar with paired parentheses.- The fully distributed expression is a first-degree polynomial in
x. 0 <= p <= m - 1.1 <= m <= 10^6.- At least one non-negative solution exists.
Similar questions at other companies
- Stack Formula InterpreterTypeSafe AI · PHONE SCREEN
- Calculate a Token-List ExpressionCollege Vine · ONSITE INTERVIEW
- Balance a Chemical EquationMicrosoft · OAMicrosoft interview questions
- Polynomial CoefficientsShopify · OAShopify interview questions
- Simplify a Quadratic ExpressionOpenAI · OAOpenAI interview questions
- Is This Date a Weekend?Salesforce · OASalesforce interview questions
- Create New VersionCisco · OACisco interview questions
- Adjacent Equal-Pair Removal GameZipRecruiter · OAZipRecruiter interview questions
- Simplified XML ValidatorAirbnb · OAAirbnb interview questions
- Parse Boolean Rule ExpressionsStripe · PHONE SCREEN · ONSITE INTERVIEWStripe interview questions