Smallest Number With Given Digit Product Problem
#2847
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2847.
You are given a positive integer n.
Return a string representing the smallest positive integer such that the product of its digits is equal to n, or "-1" if no such number exists.
Example 1:
Input: n = 105
Output: "357"
Explanation: 3 * 5 * 7 = 105. It can be shown that 357 is the smallest number with a product of digits equal to 105. So the answer would be "357".
Example 2:
Input: n = 7
Output: "7"
Explanation: Since 7 has only one digit, its product of digits would be 7. We will show that 7 is the smallest number with a product of digits equal to 7. Since the product of numbers 1 to 6 is 1 to 6 respectively, so "7" would be the answer.
Example 3:
Input: n = 44
Output: "-1"
Explanation: It can be shown that there is no number such that its product of digits is equal to 44. So the answer would be "-1".
Constraints:
1 <= n <= 10^15
Solution
Approach: Factor Into Digits Greedily
Digits 1 to 9 only have prime factors 2, 3, 5 and 7, so if n has any larger prime factor the answer is "-1".
Otherwise split n into as few digits as possible, since fewer digits means a smaller number. Divide out the digits from 9 down to 2 greedily (9 first, then 8, and so on), which merges prime factors into the largest possible digits. Then write the collected digits in ascending order to make the number as small as possible. If n = 1, the answer is "1".
Complexity: Time O(log n), space O(1).
class Solution:
def smallestNumber(self, n: int) -> str:
cnt = [0] * 10
for i in range(9, 1, -1):
while n % i == 0:
n //= i
cnt[i] += 1
if n > 1:
return "-1"
ans = "".join(str(i) * cnt[i] for i in range(2, 10))
return ans if ans else "1"