1999. Smallest Greater Multiple Made of Two Digits π
Description
Given three integers, k, digit1, and digit2, you want to find the smallest integer that is:
- Larger than
k, - A multiple of
k, and - Comprised of only the digits
digit1and/ordigit2.
Return the smallest such integer. If no such integer exists or the integer exceeds the limit of a signed 32-bit integer (231 - 1), return -1.
Example 1:
Input: k = 2, digit1 = 0, digit2 = 2 Output: 20 Explanation: 20 is the first integer larger than 2, a multiple of 2, and comprised of only the digits 0 and/or 2.
Example 2:
Input: k = 3, digit1 = 4, digit2 = 2 Output: 24 Explanation: 24 is the first integer larger than 3, a multiple of 3, and comprised of only the digits 4 and/or 2.
Example 3:
Input: k = 2, digit1 = 0, digit2 = 0 Output: -1 Explanation: No integer meets the requirements so return -1.
Constraints:
1 <= k <= 10000 <= digit1 <= 90 <= digit2 <= 9
Solutions
Solution 1
Thinking
We want the least integer greater than \(k\) that is a multiple of \(k\) and uses only two given digits. Generating multiples of \(k\) may skip many digit constraints; BFS on digits emits every legal number in order.
Sort the two digits and append either one to the current value. The queue is short-first and then lexicographic, so the first candidate \(>k\) and divisible by \(k\) is minimal. Overflow past \(2^{31}-1\) means none exists.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |