Smallest Number With Given Digit Product - Problem
Given a positive integer n, your task is to find the smallest positive integer whose digits multiply together to equal n. If no such number exists, return "-1".

This problem combines number theory with greedy algorithms. The key insight is that we want to use the largest possible digits (9, 8, 7, etc.) to minimize the total number of digits, and arrange them in ascending order to get the lexicographically smallest result.

Examples:
n = 12"26" (2 × 6 = 12, and 26 < 34)
n = 0"10" (1 × 0 = 0, smallest number with 0 as digit)
n = 1"1" (trivial case)
n = 11"-1" (11 is prime > 7, impossible)

Input & Output

example_1.py — Basic Case
$ Input: n = 12
Output: "26"
💡 Note: 12 = 2 × 6, so we need digits whose product is 12. The possible combinations are: 2×6=12, 3×4=12. Since 26 < 34, the answer is "26".
example_2.py — Zero Case
$ Input: n = 0
Output: "10"
💡 Note: To get digit product = 0, we need at least one digit to be 0. The smallest such number is "10" (1×0=0).
example_3.py — Impossible Case
$ Input: n = 11
Output: "-1"
💡 Note: 11 is a prime number greater than 7. Since digits can only be 1-9, and we need positive integers (so no leading zeros), it's impossible to form a number whose digits multiply to 11.

Constraints

  • 1 ≤ n ≤ 109
  • Return value should be a string
  • n = 0 should return "10" (special case)

Visualization

Tap to expand
Number Factory: Digit Product Assembly LineINPUTn = 72Raw MaterialFACTORIZER72 = 2³ × 3²Factor ExtractionASSEMBLERGreedy Formation→8→9Digit FormationSORTER[8,9] → [8,9]Quality ControlOUTPUT"89"Final ProductAssembly Line Process DetailsMachine 1: FactorizerExtracts prime factors2, 3, 5, 7 onlyMachine 2: Combiner9←3², 8←2³, 6←2×3Greedy largest digitsMachine 3: SorterAscending orderLexicographically smallest🏭 Factory Efficiency: O(log n) time, O(1) spaceQuality Guarantee: Always produces the smallest valid number
Understanding the Visualization
1
Input Processing
The target number n enters the factorization machine
2
Prime Breakdown
Machine extracts all factors of 2, 3, 5, and 7
3
Digit Assembly
Greedy machines combine factors into largest possible digits
4
Quality Control
Sort digits in ascending order for optimal result
Key Takeaway
🎯 Key Insight: Like an efficient factory, we break down the problem into manageable components (prime factorization), then use greedy optimization to reassemble them into the most efficient solution. The assembly line approach guarantees optimal results in minimal time!
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 22
23.4K Views
Medium-High Frequency
~18 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen