LeetCode 902: Numbers At Most N Given Digit Set Solution

Master LeetCode problem 902 (Numbers At Most N Given Digit Set), a hard 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.

902. Numbers At Most N Given Digit Set

Problem Explanation

Explanation:

To solve this problem, we can use dynamic programming. We need to count the number of positive integers that can be generated that are less than or equal to the given integer n, using the available digits. We iterate through each digit of n from left to right, considering each possible scenario based on whether the current digit is present in the given digits array or not.

  1. Initialize a dp array to store the number of valid integers that can be formed with i digits.
  2. Iterate through each digit of n from left to right, calculating the number of valid integers with i digits that are less than or equal to the current prefix of n.
  3. Finally, return the total count of valid integers by summing up the counts from all possible digit lengths.

Time Complexity: O(log(n) * digits.length)
Space Complexity: O(log(n))

:

Solution Code

class Solution {
    public int atMostNGivenDigitSet(String[] digits, int n) {
        String nStr = String.valueOf(n);
        int len = nStr.length();
        int[] dp = new int[len + 1];
        
        dp[len] = 1; // Base case when digits are exhausted
        
        for (int i = len - 1; i >= 0; i--) {
            int currDigit = nStr.charAt(i) - '0';
            for (String digit : digits) {
                if (Integer.parseInt(digit) < currDigit) {
                    dp[i] += Math.pow(digits.length, len - i - 1);
                } else if (Integer.parseInt(digit) == currDigit) {
                    dp[i] += dp[i + 1];
                }
            }
        }
        
        for (int i = 1; i < len; i++) {
            dp[0] += Math.pow(digits.length, i);
        }
        
        return dp[0];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 902 (Numbers At Most N Given Digit Set)?

This page provides optimized solutions for LeetCode problem 902 (Numbers At Most N Given Digit Set) 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 902 (Numbers At Most N Given Digit Set)?

The time complexity for LeetCode 902 (Numbers At Most N Given Digit Set) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 902 on DevExCode?

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

Back to LeetCode Solutions