Smallest Divisible Digit Product II - Problem

You're given a string num representing a positive integer and an integer t. Your mission is to find the smallest zero-free number that is greater than or equal to num and has a special property: the product of its digits must be divisible by t.

A number is zero-free if none of its digits are 0. This constraint makes the problem particularly challenging since we can't use 0 as a "filler" digit.

Goal: Return a string representing this magical number, or "-1" if no such number exists.

Example: If num = "1234" and t = 6, we need to find the smallest number ≥ 1234 with no zeros where digit product is divisible by 6. The digit product of 1234 is 1×2×3×4 = 24, and 24 ÷ 6 = 4, so "1234" itself works!

Input & Output

example_1.py — Basic Case
$ Input: num = "1234", t = 6
Output: "1234"
💡 Note: The digit product of 1234 is 1×2×3×4 = 24, and 24 is divisible by 6 (24 ÷ 6 = 4). Since 1234 ≥ 1234 and contains no zeros, it's our answer.
example_2.py — Need to Increment
$ Input: num = "1000", t = 10
Output: "1125"
💡 Note: 1000 contains zeros, so we need to find a larger zero-free number. We need digit product divisible by 10 = 2×5. The number 1125 has product 1×1×2×5 = 10, which is divisible by 10.
example_3.py — Impossible Case
$ Input: num = "1", t = 11
Output: "-1"
💡 Note: Since 11 is prime and greater than 7, and digits can only contribute prime factors 2, 3, 5, 7, it's impossible to create a digit product divisible by 11.

Constraints

  • 1 ≤ num.length ≤ 105
  • num consists of only digits and does not have leading zeros
  • 1 ≤ t ≤ 109
  • The result number should not exceed reasonable length limits

Visualization

Tap to expand
Smallest Divisible Digit Product II INPUT String num: 1 2 3 4 idx 0 idx 1 idx 2 idx 3 Target divisor t: 6 Digit Product: 1 x 2 x 3 x 4 = 24 24 mod 6 = 0 Constraint: Zero-free number ALGORITHM STEPS 1 Factorize t 6 = 2 x 3 Need factors: 2, 3 2 Check Current Product Product(1,2,3,4) = 24 24 has factors 2,3 3 Divisibility Check 24 % 6 == 0 ? YES - divisible! 4 Validate Result No zeros in num Already minimal Decision: Return original num FINAL RESULT Output String: 1 2 3 4 OK - Valid! Verification: Product: 1x2x3x4 = 24 t = 6 24 / 6 = 4 (exact) Divisible: YES Answer: "1234" Key Insight: For digit product divisibility, we need the product to contain all prime factors of t. The optimal approach checks if current num already satisfies the condition. If not, we increment digits from right to left while avoiding zeros. Here, 1x2x3x4=24 is divisible by 6, so "1234" is the answer. TutorialsPoint - Smallest Divisible Digit Product II | Optimal Solution
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
28.4K Views
Medium Frequency
~35 min Avg. Time
892 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