Problem Description
Given a positive integer n, find the smallest positive integer (represented as a string) such that the product of its digits equals n. If no such number exists, return "-1".
Key Insights
- For numbers less than 10, the answer is simply the number itself.
- Factorize n by attempting to divide by digits from 9 down to 2. This is because digits closer to 9 will provide the least number of factors, but later the sorted order will yield the smallest possible number.
- If after factorization n is not reduced to 1, it means n has a prime factor greater than 9 and no valid factorization exists.
- Sorting the collected factors in increasing order will construct the smallest possible number.
Space and Time Complexity
Time Complexity: O(log n) in most cases, because n is divided repeatedly by factors between 2 and 9. Space Complexity: O(1), as only a constant amount of extra space is used aside from the output.
Solution
The solution employs a greedy strategy by trying to factorize the given number using digits 9 to 2. Each time a digit divides the number exactly, we record that digit and update the number. After factorization, if the number is not 1, a valid factorization is not possible, so we return "-1". Otherwise, we sort the list of factors in ascending order to form the smallest integer. This approach leverages simple arithmetic operations and sorting a small list of factors, making it efficient given the constraints.