Smallest Number With Given Digit Product - 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.

If no such number exists, return "-1".

Note: The returned number should be as small as possible, which means it should have the fewest digits, and among numbers with the same number of digits, it should be lexicographically smallest.

Input & Output

Example 1 — Basic Case
$ Input: n = 12
Output: 26
💡 Note: We need digits that multiply to 12. Using greedy approach: 12 = 6 × 2. Sort digits: [2,6] → "26"
Example 2 — Single Digit
$ Input: n = 1
Output: 1
💡 Note: Special case: the smallest number with digit product 1 is 1 itself
Example 3 — Impossible Case
$ Input: n = 11
Output: -1
💡 Note: 11 is prime and > 9, so it cannot be expressed as a product of single digits (2-9)

Constraints

  • 1 ≤ n ≤ 109

Visualization

Tap to expand
Smallest Number With Given Digit Product INPUT Given Number n = 12 Find smallest number where digit product equals n Example: 26 2 x 6 = 12 Product matches n Valid digits: 2-9 (1 doesn't reduce n, 0 makes product 0) ALGORITHM STEPS 1 Start from digit 9 Try largest digits first 2 Factorize n 12 / 6 = 2 (use 6) 3 Continue dividing 2 / 2 = 1 (use 2) 4 Sort digits Ascending for smallest Greedy Factorization n=12: 12%9!=0, 12%8!=0 12%7!=0, 12%6=0 ---> digit: 6 n=2: 2%2=0 ---> digit: 2 FINAL RESULT Collected Digits: 6 2 Sort ascending: 2 6 Output: 26 OK: 2 x 6 = 12 Key Insight: Use greedy factorization from 9 down to 2. Larger digits mean fewer total digits. Sort collected digits ascending to form the lexicographically smallest number. Return -1 if n has prime factors greater than 9 (cannot be represented by single digits). TutorialsPoint - Smallest Number With Given Digit Product | Greedy Factorization
Asked in
Google 15 Amazon 12 Microsoft 8
23.0K Views
Medium Frequency
~15 min Avg. Time
890 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