Python 1015.py
class Solution:
def smallestRepunitDivByK(self, k: int) -> int:
# multiples of 2 and/or 5 never end with "1"
if k % 2 == 0 or k % 5 == 0:
return -1
# https://oeis.org/A067063
# repunit(k - 1) or repunit(k) is always a multiple of k if such a relation exists
# maybe there is a smaller solution but definitely never a need to look beyond k
# honestly this problem stinks because it's very simple programming
# but you need a math knowledge not taught outside university math courses
# on top, I have no idea how to solve this in C/C++ where numbers must fit in 64 bit
ones = 1
for i in range(1, k + 1):
if ones % k == 0:
return i
ones *= 10
ones += 1
return -1
Difficulty
and has an acceptance rate of about 54% (300k+ submissions).
Typical patterns to solve this problem:
- Hash Table
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method smallestRepunitDivByK that determines the length of the smallest repunit (a number consisting solely of the digit 1) that is divisible by a given integer k. If no such repunit exists, the method returns -1. The algorithm relies on modular arithmetic to avoid constructing the potentially huge repunit explicitly, iterating at most k times.
Core Logic
The method begins by eliminating values of k that can never divide a repunit. Because any repunit ends with the digit 1, it cannot be divisible by 2 or 5. This early exit is performed with a simple modulus check:
if k % 2 == 0 or k % 5 == 0:
return -1
After this guard, the algorithm initializes a variable ones to represent the current repunit value modulo k. Starting with the single-digit repunit 1, the loop iterates from 1 up to k inclusive. In each iteration it checks whether the current ones value is divisible by k. If the condition holds, the loop index i-which corresponds to the length of the repunit- is returned:
if ones % k == 0:
return i
If the condition is not satisfied, the algorithm builds the next repunit by shifting the current value one decimal place to the left (multiplying by 10) and adding another 1. Because the variable ones is kept as a plain integer, the operation implicitly computes the full repunit, but the subsequent modulus test ensures that only the remainder matters for the divisibility decision:
ones *= 10
ones += 1
If the loop completes without finding a divisor, the method returns -1, indicating that no repunit of length up to k divides k. The comment in the source notes that a solution, if it exists, will be found within k iterations, based on number-theoretic properties of repunits.
Edge Cases Handled
The early return for even k or multiples of five directly addresses the case where a repunit can never be a multiple of k. This prevents unnecessary computation for inputs such as k = 2, k = 4, k = 10, etc.
When k is 1, the initial ones value of 1 satisfies the divisibility test on the first iteration, causing the method to return 1. This correctly identifies that the single-digit repunit is divisible by 1.
The loop bound k + 1 ensures that the algorithm examines repunits of length exactly k. According to the underlying mathematical theorem, if a repunit divisible by k exists, its length will not exceed k. Consequently, the method safely returns -1 only after exhausting all feasible lengths.
Performance Optimizations
The most notable optimization is the avoidance of constructing the full repunit as a string or a large integer. By maintaining ones as an integer and applying the modulus operation at each step, the algorithm leverages the fact that only the remainder modulo k influences the divisibility outcome. This keeps the intermediate values bounded by the size of k and prevents exponential growth of the numeric representation.
The early exit for factors of 2 and 5 eliminates entire classes of inputs from the main loop, saving time for half of the possible integer values.
Iterating at most k times provides a deterministic upper bound on runtime, guaranteeing termination without resorting to more complex cycle detection or mathematical shortcuts. The straightforward arithmetic inside the loop-multiplication by 10, addition of 1, and a modulus check-are all constant-time operations on typical Python integers, contributing to a tight execution path.
Overall, the method balances mathematical insight with minimalistic code, delivering an efficient solution for the problem of finding the smallest repunit divisible by a given integer.
ELI5 - Simplified Explanation
Imagine you have a long, long string of the number one, like 1, 11, 111, and so on. This code is playing a game to see which of those strings can be perfectly chopped into equal pieces by the number you picked.
The first part of the code acts like a guard. If your number ends in a zero, a two, a four, a five, a six, or an eight, it knows right away that a string of ones will never be able to fit perfectly into your number. It stops the game early and says it is not possible.
If the number passes that check, the code starts building a longer and longer string of ones. It keeps track of the current string and tries to divide it by your chosen number. If there is no piece left over, it knows it found the right string of ones and says how many ones it used to get there. It keeps adding one more digit to the string of ones, step by step, until it finds the fit or realizes it has gone far enough to know it will never happen.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| withaarzoo | C++ | ||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 483: Smallest Good Base
Solved On The Same Day
- problem 830: Positions of Large Groups
- problem 1566: Detect Pattern of Length M Repeated K or More Times
- problem 2437: Number of Valid Clock Times
- problem 1016: Binary String With Substrings Representing 1 To N
- problem 1254: Number of Closed Islands
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality