LeetCode 2847: Smallest Number With Given Digit Product Solution

Master LeetCode problem 2847 (Smallest Number With Given Digit Product), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2847. Smallest Number With Given Digit Product

Problem Explanation

Explanation

To find the smallest number with a given digit product n, we can start from 1 and keep multiplying the digits to form numbers until we reach a number whose product of digits is equal to n. We need to ensure that the number is minimized by forming the smallest possible digits at each step.

Algorithm:

  1. Initialize an empty list digits.
  2. Iterate from 9 to 2:
    • While n is divisible by the current digit i, add i to the digits list and update n by dividing it by i.
  3. If n is still greater than 1, return -1 (no such number exists).
  4. Otherwise, sort the digits list in ascending order and construct the smallest number from the digits.

Time Complexity:

The time complexity of this algorithm is O(9log9) = O(1) as the loop runs a constant number of times.

Space Complexity:

The space complexity is O(1) as we are using a fixed-size list to store the digits.

Solution Code

class Solution {
    public int smallestNumber(int n) {
        if (n == 1) return 1;

        List<Integer> digits = new ArrayList<>();
        for (int i = 9; i > 1; i--) {
            while (n % i == 0) {
                digits.add(i);
                n /= i;
            }
        }

        if (n > 1) return -1;

        Collections.sort(digits);
        int result = 0;
        for (int digit : digits) {
            result = result * 10 + digit;
        }

        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2847 (Smallest Number With Given Digit Product)?

This page provides optimized solutions for LeetCode problem 2847 (Smallest Number With Given Digit Product) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2847 (Smallest Number With Given Digit Product)?

The time complexity for LeetCode 2847 (Smallest Number With Given Digit Product) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2847 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2847 in Java, C++, or Python.

Back to LeetCode Solutions