Smallest All-Ones Multiple Problem
Description
LeetCode Problem 3790.
You are given a positive integer k.
Find the smallest integer n divisible by k that consists of only the digit 1 in its decimal representation (e.g., 1, 11, 111, ...).
Return an integer denoting the number of digits in the decimal representation of n. If no such n exists, return -1.
Example 1:
Input: k = 3
Output: 3
Explanation:
n = 111 because 111 is divisible by 3, but 1 and 11 are not. The length of n = 111 is 3.
Example 2:
Input: k = 7
Output: 6
Explanation:
n = 111111. The length of n = 111111 is 6.
Example 3:
Input: k = 2
Output: -1
Explanation:
There does not exist a valid n that is a multiple of 2.
Constraints:
2 <= k <= 10^5
Solution
Approach: Simulation with Remainders
The all-ones numbers get huge, but we only need their remainders modulo k. Appending a digit 1 to a number with remainder x gives remainder (x * 10 + 1) % k, so we can build 1, 11, 111, ... one digit at a time with small numbers.
An even k can never divide a number ending in 1, so we return -1 right away. Otherwise there are only k possible remainders, so if no remainder becomes 0 within k steps the remainders repeat forever and the answer is -1. When the remainder hits 0, the number of digits built so far is the answer.
Complexity: O(k) time and O(1) extra space.
class Solution:
def minAllOneMultiple(self, k: int) -> int:
if k % 2 == 0:
return -1
x = 1 % k
ans = 1
for _ in range(k):
x = (x * 10 + 1) % k
ans += 1
if x == 0:
return ans
return -1