#3348

Smallest Divisible Digit Product II

Hard
MathStringBacktrackingGreedyNumber TheoryGreedy ApproachBacktracking
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)

The optimal approach involves modifying the digits of 'num' directly to find the smallest zero-free number that meets the product condition. This is more efficient as it avoids unnecessary checks and focuses on the digits that need to be changed.

⚙️

Algorithm

5 steps
  1. 1Step 1: Convert 'num' to a list of digits.
  2. 2Step 2: Calculate the product of the digits and check if it is divisible by 't'.
  3. 3Step 3: If not, iterate from the last digit to find the first digit that can be increased to make the product divisible by 't'.
  4. 4Step 4: Increment this digit and set all subsequent digits to '1' to minimize the number.
  5. 5Step 5: If the resulting number is valid (zero-free), return it; otherwise, return '-1'.
solution.py26 lines
1# Full working Python code
2
3def smallest_divisible_digit_product(num, t):
4    digits = list(map(int, num))
5    product = 1
6    for d in digits:
7        product *= d
8    if product % t == 0:
9        return num
10
11    for i in range(len(digits) - 1, -1, -1):
12        if digits[i] < 9:
13            digits[i] += 1
14            for j in range(i + 1, len(digits)):
15                digits[j] = 1
16            new_num = ''.join(map(str, digits))
17            if '0' not in new_num and product_of_digits(new_num) % t == 0:
18                return new_num
19            break
20    return '-1'
21
22def product_of_digits(num):
23    product = 1
24    for digit in num:
25        product *= int(digit)
26    return product

Complexity note: The time complexity is O(n) because we only iterate through the digits a limited number of times, and the space complexity is O(n) for storing the digits.

  • 1Understanding the properties of digit products and their divisibility can help optimize the search.
  • 2Incrementing digits from the least significant to the most allows for minimal changes to achieve the desired product.

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