Smallest Integer Divisible by K - 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
  • 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, so we work with remainders using modular arithmetic.

Examples of numbers containing only 1s: 1, 11, 111, 1111, 11111...

Input & Output

example_1.py โ€” Basic Case
$ Input: k = 1
โ€บ Output: 1
๐Ÿ’ก Note: The smallest integer containing only 1s that is divisible by 1 is just '1' itself, which has length 1.
example_2.py โ€” Small Prime
$ Input: k = 3
โ€บ Output: 3
๐Ÿ’ก Note: We check: 1%3=1, 11%3=2, 111%3=0. So '111' is the first number containing only 1s divisible by 3, with length 3.
example_3.py โ€” Impossible Case
$ Input: k = 2
โ€บ Output: -1
๐Ÿ’ก Note: Any number containing only 1s is odd, so it can never be divisible by 2. Return -1.

Visualization

Tap to expand
๐Ÿ• Digital Clock Repunit Finder1Length: 111Length: 2111Length: 31111Length: 4Modular Arithmetic Magic โœจFor k=3:โ€ข remainder = (0 * 10 + 1) % 3 = 1โ€ข remainder = (1 * 10 + 1) % 3 = 2โ€ข remainder = (2 * 10 + 1) % 3 = 0 โœ“Answer: Length 3For k=2:โ€ข 2 is even โ†’ Impossible!โ€ข All repunits are oddAnswer: -1
Understanding the Visualization
1
Check Feasibility
If k divisible by 2 or 5, impossible (repunits are always odd and never end in 0/5)
2
Build Remainders
Instead of huge numbers, track remainder = (remainder * 10 + 1) % k
3
Detect Success
When remainder becomes 0, we found our answer
4
Detect Cycles
If we see same remainder twice, no solution exists
Key Takeaway
๐ŸŽฏ Key Insight: Use modular arithmetic to track remainders instead of building massive numbers, and detect cycles to determine when no solution exists.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(k)

At most k different remainders possible, so we'll find answer or cycle within k iterations

n
2n
โœ“ Linear Growth
Space Complexity
O(k)

Hash set to store seen remainders, at most k different values

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค k โ‰ค 105
  • k is a positive integer
  • Time limit: Solution must run within reasonable time for all valid inputs
Asked in
Google 15 Amazon 8 Meta 5 Microsoft 3
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen