Leetcode 1015: Smallest Integer Divisible by K

grid47
grid47
Exploring patterns and algorithms
Jul 28, 2024 5 min read

Given a positive integer k, find the length of the smallest positive integer n such that n is divisible by k, and n consists only of the digit 1. If no such number exists, return -1. Note that n might not fit into a 64-bit signed integer.
Problem
Approach
Steps
Complexity
Input: The input consists of a single integer k, where k is a positive integer.
Example: k = 7
Constraints:
• 1 <= k <= 10^5
Output: The output should be an integer representing the length of the smallest integer n that is divisible by k and only contains the digit 1, or -1 if no such integer exists.
Example: Output: 6
Constraints:
• The result must be an integer.
Goal: To determine the length of the smallest integer n that is divisible by k and consists only of the digit 1.
Steps:
• Iterate through possible lengths of numbers formed only by the digit 1.
• For each length, compute the number formed by that many 1s, and check if it's divisible by k.
• Return the length of the first such number, or -1 if no such number exists.
Goal: The solution needs to handle large values of k efficiently.
Steps:
• The value of k can be as large as 100,000, requiring an efficient solution to avoid brute force checks for large numbers.
Assumptions:
• There is always a valid input integer k, and it will be between 1 and 100,000.
Input: Input: k = 1
Explanation: The smallest number divisible by 1 is simply 1, which has length 1.

Input: Input: k = 2
Explanation: There is no number formed by 1s that is divisible by 2, so the output is -1.

Input: Input: k = 3
Explanation: The smallest number divisible by 3 is 111, which has length 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus