#1015

Smallest Integer Divisible by K

Medium
Hash TableMathBreadth-First SearchHash Set
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of generating large numbers, we can track remainders when we build the number. This way, we avoid overflow and can find the answer using a breadth-first search approach.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a queue to perform a breadth-first search starting with the number '1'.
  2. 2Step 2: Maintain a set to track visited remainders to avoid cycles.
  3. 3Step 3: For each number, calculate the new number by appending '1' and compute the new remainder.
  4. 4Step 4: If the remainder is 0, return the current length. If not, enqueue the new number if its remainder hasn't been seen before.
solution.py14 lines
1from collections import deque
2
3def smallestIntegerDivisibleByK(k):
4    queue = deque([(1, 1)])  # (current number, length)
5    visited = set()
6    while queue:
7        n, length = queue.popleft()
8        if n % k == 0:
9            return length
10        remainder = n % k
11        if remainder not in visited:
12            visited.add(remainder)
13            queue.append((remainder * 10 + 1, length + 1))
14    return -1

Complexity note: The time complexity is O(n) because we explore each remainder at most once. The space complexity is O(n) due to the queue and visited set.

  • 1The problem can be solved using breadth-first search to avoid overflow and efficiently find the solution.
  • 2Tracking remainders helps in determining divisibility without generating large numbers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.