MediumNo. 1015

Smallest Integer Divisible by K — LeetCode 1015 Python Solution

Topics
Hash Table, Math
Reading time
2 min

The problem

Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1. Return the length of n.

Example

Input
k = 1
Output
1
Explanation
The smallest answer is n = 1, which has length 1.

Python solution

PythonSolution
class Solution:
    def smallestRepunitDivByK(self, k: int) -> int:
        n = 1 % k
        for i in range(1, k + 1):
            if n == 0:
                return i
            n = (n * 10 + 1) % k
        return -1

Complexity

Time
O(k)
Space · auxiliary
O(1)where k is the given positive integer

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1015. Smallest Integer Divisible by K is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0012Integer to RomanMedium
0013Roman to IntegerEasy
0149Max Points on a LineHard
0166Fraction to Recurring DecimalMedium
0202Happy NumberEasy
0264Ugly Number IIMedium

Frequently asked questions

How hard is LeetCode 1015. Smallest Integer Divisible by K?

LeetCode 1015. Smallest Integer Divisible by K is rated Medium on LeetCode.

What is the time complexity of LeetCode 1015. Smallest Integer Divisible by K?

The Python solution on this page runs in O(k).

What is the space complexity of LeetCode 1015. Smallest Integer Divisible by K?

The Python solution on this page uses O(1), where k is the given positive integer auxiliary space.

What topics does LeetCode 1015. Smallest Integer Divisible by K cover?

LeetCode 1015. Smallest Integer Divisible by K is tagged Hash Table and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.