Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Smallest Integer Divisible by K

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1015" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

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. If there is no such n, return -1. Note: n may not fit in a 64-bit signed integer. Example 1: Input: k = 1 Output: 1 Explanation: The smallest answer is n = 1, which has length 1. Example 2: Input: k = 2 Output: -1 Explanation: There is no such positive integer n divisible by 2. Example 3: Input: k = 3 Output: 3 Explanation: The smallest answer is n = 111, which has length 3. Constraints: 1 <= k <= 105

Explanation

Here's the breakdown of the solution:

  • Modular Arithmetic: We use the property that if (a * 10 + 1) % k == 0, then a number consisting of '1's is divisible by k. We iteratively build such numbers modulo k.
  • Pigeonhole Principle: If we encounter the same remainder twice, it means there's a cycle and no solution exists. We use a seen set to keep track of remainders.
  • Iteration and Check: We start with remainder = 0 and length 1, and in each iteration, we update the remainder by adding 1 to the current number formed of all ones and take the modulo k. We check if the remainder is zero, meaning we found our number. If we have already seen a remainder, that indicates there is a cycle and we exit early.

  • Time and Space Complexity: O(k) time, O(k) space

Code

    def smallest_repunit_divByK(k: int) -> int:
    """
    Given a positive integer k, 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. If there is no such n, return -1.
    Note: n may not fit in a 64-bit signed integer.

    For example:
    smallest_repunit_divByK(1) == 1
    smallest_repunit_divByK(2) == -1
    smallest_repunit_divByK(3) == 3
    """
    if k % 2 == 0 or k % 5 == 0:
        return -1

    remainder = 0
    length = 0
    seen = set()

    for length in range(1, k + 1):
        remainder = (remainder * 10 + 1) % k
        if remainder == 0:
            return length
        if remainder in seen:
            return -1
        seen.add(remainder)

    return -1

More from this blog

C

Chatmagic blog

2894 posts