|
| 1 | +# Smallest Integer Divisible by K (Medium) |
| 2 | + |
| 3 | +**Problem ID:** 1015 |
| 4 | +**Date:** 2025-11-25 |
| 5 | +**Link:** https://leetcode.com/problems/smallest-integer-divisible-by-k/ |
| 6 | + |
| 7 | +## Approach |
| 8 | + |
| 9 | +To solve the problem of finding the length of the smallest positive integer \( n \) that consists solely of the digit '1' and is divisible by a given integer \( k \), we can utilize a breadth-first search (BFS) approach to explore potential candidates for \( n \). |
| 10 | + |
| 11 | +### Approach: |
| 12 | + |
| 13 | +1. **Understanding the Problem**: |
| 14 | + - The number \( n \) can be represented as a sequence of '1's: \( 1, 11, 111, \ldots \). The goal is to find the smallest such number that is divisible by \( k \). |
| 15 | + |
| 16 | +2. **Using Modulo for Divisibility**: |
| 17 | + - Instead of generating large numbers directly, we can work with their remainders when divided by \( k \). This is because if \( n \equiv 0 \mod k \), then \( n \) is divisible by \( k \). |
| 18 | + |
| 19 | +3. **BFS for Exploration**: |
| 20 | + - We can treat each number formed by '1's as a node in a graph. Starting from the number '1', we can generate new numbers by appending another '1' to the current number. |
| 21 | + - For each number represented by its remainder \( r \) (where \( r = n \mod k \)), we can generate two new remainders: |
| 22 | + - \( (r \times 10 + 1) \mod k \) (this represents appending another '1'). |
| 23 | + - We will keep track of the length of the number (or the number of '1's) in the BFS queue. |
| 24 | + |
| 25 | +4. **Cycle Prevention**: |
| 26 | + - To avoid processing the same remainder multiple times, we maintain a set of visited remainders. |
| 27 | + |
| 28 | +5. **Termination**: |
| 29 | + - The BFS continues until we either find a remainder of \( 0 \) (indicating divisibility by \( k \)) or exhaust all possibilities without finding such a remainder. |
| 30 | + |
| 31 | +### Data Structures: |
| 32 | +- A queue to facilitate the BFS process. |
| 33 | +- A set to track visited remainders to prevent cycles. |
| 34 | + |
| 35 | +### Time Complexity: |
| 36 | +- The time complexity is \( O(k) \) since there are at most \( k \) different remainders (from \( 0 \) to \( k-1 \)) that we can encounter. |
| 37 | + |
| 38 | +### Space Complexity: |
| 39 | +- The space complexity is also \( O(k) \) due to the storage of visited remainders. |
| 40 | + |
| 41 | +### Conclusion: |
| 42 | +By using BFS and focusing on remainders rather than constructing large numbers, we efficiently find the length of the smallest integer composed solely of '1's that is divisible by \( k \). If no such integer exists, we return -1. |
0 commit comments