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
Prime Factor Distribution Strategyt = 602² × 3 × 5Factor 2²Factor 3Factor 54provides 2²3provides 35provides 5Result: "435"Product = 4 × 3 × 5 = 60✓ Divisible by t = 60
Understanding the Visualization
1
Factor Analysis
Break t = 60 into prime factors: 2² × 3 × 5
2
Digit Mapping
Map each digit to its prime factors: 6 = 2×3, 4 = 2², etc.
3
Greedy Assignment
Try to use the smallest digits that provide the required factors
4
Validation
Ensure the result is ≥ input number and zero-free
Key Takeaway
🎯 Key Insight: Only prime factors 2, 3, 5, 7 can be formed from digits 1-9. Use backtracking to distribute these factors optimally across digit positions, building the smallest valid number systematically.
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