Problem · String

Smallest Value for a Linear Expression Modulo

Learn this problem
HardIntel logoIntelFULLTIMEOA

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) → int

Examples

Example 1

expression = "4+x+2"p = 8m = 9return = 2

The 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 = 1

The 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.
  • expression follows 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.
drafts saved locally
public int smallestNonnegativeX(String expression, int p, int m) {
    // Parse the expression and solve the resulting congruence.
}
expression"4+x+2"
p8
m9
expected2
checking account