Problem 1015

Abstract / Summary

Find the smallest positive integer that is divisible by a given number k using its digits only once.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
24 lines | 847 bytes | submitted October 14, 2023 | GitHub   63% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (300k+ submissions).

Typical patterns to solve this problem:
  • Hash Table
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.92 | σ = 1.27

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
33 links | 19 authors | 8 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

6 solutions   October 14, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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