{x}
blog image

Minimum Factorization

Solution Explanation for Minimum Factorization

The problem asks to find the smallest positive integer whose product of digits equals a given number num. If no such integer exists or the result exceeds the 32-bit signed integer limit, return 0.

The solution employs a greedy approach. We iterate through digits from 9 down to 2. For each digit, we check if it's a factor of the current num. If it is, we repeatedly divide num by that digit until it's no longer divisible. Each time we successfully divide, we append the digit to the result (ans) by constructing it digit by digit.

Algorithm:

  1. Handle Base Cases: If num is less than 2, return num directly.

  2. Greedy Iteration: Iterate from 9 down to 2. This order is crucial for finding the smallest possible integer.

  3. Factor Check: For each digit i, check if num is divisible by i.

  4. Repeated Division: If divisible, repeatedly divide num by i while building the result:

    • Multiply the existing ans by 10 to shift digits to the left.
    • Add i to ans.
  5. Final Check: After the loop, if num is reduced to 1 (all factors found) and the constructed ans is within the 32-bit signed integer range, return ans. Otherwise, return 0.

Time Complexity Analysis:

The time complexity is dominated by the outer loop iterating from 9 down to 2. The inner while loop executes a maximum of log2(num) times (since each division halves the number approximately). Therefore, the overall time complexity is O(log2(num)). In the worst case, the number has many small prime factors, causing the inner loop to run multiple times.

Space Complexity Analysis:

The space complexity is O(1) because we use only a constant number of variables to store the result and intermediate values.

Code Explanation (Python):

class Solution:
    def smallestFactorization(self, num: int) -> int:
        if num < 2:
            return num
        ans, mul = 0, 1  # ans stores the result, mul keeps track of the multiplier (powers of 10)
        for i in range(9, 1, -1): #Iterate from 9 down to 2
            while num % i == 0: #check divisibility
                num //= i  #divide num by i
                ans = mul * i + ans #construct ans digit by digit
                mul *= 10 #multiply mul by 10 for next digit
        return ans if num < 2 and ans <= 2**31 - 1 else 0 #final check for num and range

The other languages (Java, C++, Go) follow the same logic with minor syntactic differences to handle data types and integer limits. The core algorithm remains consistent across all implementations.