Minimum Factorization Problem
Description
LeetCode Problem 625.
Given a positive integer num, return the smallest positive integer x whose multiplication of each digit equals num. If there is no answer or the answer is not fit in 32-bit signed integer, return 0.
Example 1:
Input: num = 48
Output: 68
Example 2:
Input: num = 15
Output: 35
Constraints:
1 <= num <= 2^31 - 1
Solution
Approach: Greedy, Largest Digits First
We need digits from 2 to 9 whose product is num (a digit 1 never helps, it only makes the number longer). Among all such digit sets, the smallest number is the one with the fewest digits, and among those, the one with its digits in increasing order.
Fewer digits means each digit should carry as much of the product as possible, so we divide out large digits first: try 9, then 8, down to 2, dividing num by each as long as it divides evenly. For example 48 = 8 * 6 (two digits) is better than 48 = 2 * 4 * 6 or 3 * 4 * 4. Taking 9 before 3 and 8 before 4 or 2 is what keeps the count of digits minimal: two 3s should always become one 9, three 2s one 8, and so on.
The digits come out from largest to smallest, so we place each one at the low end of the answer: keep a place value starting at 1, add digit * place and multiply place by 10. The largest digits end up on the right, giving the digits in increasing order, which is the smallest arrangement.
Two cases return 0:
- After dividing out all digits,
numis still greater than1. Then it has a prime factor above7(like11), which no digit can produce. - The answer does not fit in a 32-bit signed integer. Build it in a 64-bit integer so the check itself does not overflow (for example
2^30gives8888888888).
A num below 10 is already a single digit and is its own answer, including num = 1.
Complexity: O(log num) time, since every division makes num at least twice smaller, and O(1) space.
class Solution:
def smallestFactorization(self, num: int) -> int:
if num < 10:
return num # a single digit is its own answer
ans, place = 0, 1
# Take the largest digits first; they go at the low end of the number.
for d in range(9, 1, -1):
while num % d == 0:
num //= d
ans += d * place
place *= 10
if num > 1 or ans > 2**31 - 1:
return 0 # a prime factor above 7 is left, or the answer is too big
return ans