Space
Open
From Fieldwork
Scales
Archive
The pedagogical value of this question is about reducing the problem to a certain state and recognizing that we can perform transformations on a smaller subset of the true data, but it's still reflective of truth because we are able to get to the part of the problem that actually matters.
This problem relies on modular arithmetic and the Pigeonhole Principle.
We are looking for the smallest n such that a number consisting only of 1s (e.g., 1, 11, 111, ...) is divisible by K.
Key Insights:
Divisibility Rule: If K is a multiple of 2 or 5, it is impossible for any number ending in 1 to be divisible by K. In these cases, we can immediately return -1.
Remainder Cycle: Instead of calculating massive numbers, we can calculate the remainder at each step.
Stopping Condition: If we see the same remainder twice, we've entered a cycle and will never reach 0. By the Pigeonhole Principle, since there are only K possible remainders (0 to K-1), if you haven't found a remainder of 0 within K iterations, it doesn't exist.
class Solution:
def smallestRepunitDivByK(self, k: int) -> int:
# If k is even or divisible by 5, no number ending in 1 can be divisible by it
if k % 2 == 0 or k % 5 == 0:
return -1
remainder = 0
# The length of n can at most be k
for length in range(1, k + 1):
# Update the remainder: (previous_remainder * 10 + 1) % k
remainder = (remainder * 10 + 1) % k
# If remainder is 0, we found the smallest n
if remainder == 0:
return length
return -1Practice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode