MediumNo. 2847LeetCode Premium

Smallest Number With Given Digit Product — LeetCode 2847 Python Solution

Pattern
Greedy
Topics
Greedy, Math
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

PythonSolution
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

Time
O(log n)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
2844Minimum Operations to Make a Special NumberMedium
0670Maximum SwapMedium
0738Monotone Increasing DigitsMedium
0910Smallest Range IIMedium
0976Largest Perimeter TriangleEasy
0991Broken CalculatorMedium

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.

Free to download. Check it runs on your machine, then pick a plan.