Smallest Number With Given Digit Product — LeetCode 2847 Python Solution
- Problem
- #2847
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(\log n) |
| Space | O(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.