#3790
Smallest All-Ones Multiple
MediumHash TableMathHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Use modular arithmetic to build the number incrementally without generating large integers. This reduces the problem to tracking remainders.
⚙️
Algorithm
3 steps- 1Step 1: Initialize rem as 1 % k and count as 1.
- 2Step 2: While rem is not 0, update rem = (rem * 10 + 1) % k and increment count.
- 3Step 3: If rem becomes 0, return count; otherwise, if count exceeds k, return -1.
solution.py9 lines
1def smallestAllOnesMultiple(k):
2 rem = 1 % k
3 count = 1
4 while rem != 0:
5 rem = (rem * 10 + 1) % k
6 count += 1
7 if count > k:
8 return -1
9 return countℹ
Complexity note: This approach only tracks remainders, making it efficient in both time and space.
- 1Only numbers with odd digits can be multiples of even k.
- 2Using modular arithmetic prevents overflow.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.