We are given a string a representing a non-negative integer and a positive integer b. The string a consists of decimal digits (0–9) and wildcard characters (x). For example, x1x could become 212, 010, or 999.
Each occurrence of x can be replaced independently with any decimal digit from 0 to 9. Different occurrences of x may be replaced with different digits.
Determine whether there exists a replacement of all occurrences of x such that the resulting number is divisible by b and is not equal to zero.
Leading zeros are allowed.
Write an optimal algorithm that returns a Boolean value:
trueif at least one valid replacement exists.falseotherwise.
A brute-force approach that tries every possible combination of digits is not considered optimal, because the number of combinations grows exponentially with the number of occurrences of x. I am looking for an efficient algorithm that can handle long input strings and arbitrary positive divisors b.
Examples
Example 1
Input:
a = "4x"
b = 5
Output:
true
Explanation: Replacing x with 0 gives 40, which is divisible by 5 and is not zero.
Example 2
Input:
a = "xx2"
b = 10
Output:
false
Explanation: Every number ending in 2 has a remainder of 2 when divided by 10, so no replacement can satisfy the divisibility condition.