Smallest Integer Divisible by K — LeetCode 1015 Python Solution

MediumHash TableMath
Problem
#1015
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

Python
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

MeasureComplexity
TimeO(k)
SpaceO(1), where k is the given positive integer auxiliary

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

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.

Get Stealth Interview