Smallest Number With Given Digit Product — LeetCode 2847 Python Solution

MediumLeetCode PremiumGreedyMath
Problem
#2847
Pattern
Greedy
Reading time
2 min

The problem

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

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".

Python solution

Python
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"

Complexity

MeasureComplexity
TimeO(\log n)
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2847. Smallest Number With Given Digit Product is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2847. Smallest Number With Given Digit Product?
LeetCode 2847. Smallest Number With Given Digit Product is rated Medium on LeetCode.
What is the time complexity of LeetCode 2847. Smallest Number With Given Digit Product?
The Python solution on this page runs in O(\log n).
What is the space complexity of LeetCode 2847. Smallest Number With Given Digit Product?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2847. Smallest Number With Given Digit Product cover?
LeetCode 2847. Smallest Number With Given Digit Product is tagged Greedy and Math on LeetCode.
Is LeetCode 2847. Smallest Number With Given Digit Product a premium problem?
Yes. LeetCode 2847. Smallest Number With Given Digit Product is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview