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.

Input & Output

Example 1 — Basic Case
$ Input: k = 1
Output: 1
💡 Note: The smallest integer containing only 1's that is divisible by 1 is "1" itself, which has length 1.
Example 2 — Requires Multiple 1's
$ Input: k = 3
Output: 3
💡 Note: We need to find the smallest number with only 1's divisible by 3: 1%3=1, 11%3=2, 111%3=0. So "111" with length 3 is the answer.
Example 3 — Impossible Case
$ Input: k = 2
Output: -1
💡 Note: Numbers containing only 1's are always odd, so they can never be divisible by 2. Return -1.

Constraints

  • 1 ≤ k ≤ 105

Visualization

Tap to expand
Problem: Find Length of Smallest Integer (only 1's) Divisible by kInputk = 3Find smallest number with only 1's:1 % 3 = 1 ❌11 % 3 = 2 ❌111 % 3 = 0 ✓Found: 111 (length = 3)Output3Impossible Case:k = 2 or k = 5Return -1Key Insight:Use modular arithmeticto avoid large numbersAlgorithm tracks remainders: 1%k → (1*10+1)%k → (result*10+1)%k until remainder = 0
Understanding the Visualization
1
Input
Given positive integer k
2
Process
Find smallest number with only 1's divisible by k
3
Output
Return length of that number, or -1 if impossible
Key Takeaway
🎯 Key Insight: Use modular arithmetic to track remainders instead of building actual large numbers
Asked in
Google 15 Facebook 12
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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