Count N-digit numbers that contains every possible digit atleast once
Given a positive integer N, the task is to count the number of N-digit numbers such that every digit from [0-9] occurs at least once.
Input: N = 10
Output : 3265920
Input: N = 5
Explanation: Since the number of digits is less than the minimum number of digits required [0-9], the answer is 0.
Naive Approach: The simplest approach to solve the problem is to generate over all possible N-digit numbers and for each such number, check if all its digits satisfy the required condition or not.
Time Complexity: O(10N*N)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Dynamic Programming as it has overlapping subproblems and optimal substructure. The subproblems can be stored in dp table using memoization, where dp[digit][mask] stores the answer from the digitth position till the end, when the included digits are represented using a mask.
Follow the steps below to solve this problem:
- Define a recursive function, say countOfNumbers(digit, mask), and perform the following steps:
- Base Case: If the value of digit is equal to N+1, then check if the value of the mask is equal to (1 << 10 – 1). If found to be true, return 1 as a valid N-digit number is formed.
- If the result of the state dp[digit][mask] is already computed, return this state dp[digit][mask].
- If the current position is 1, then any digit from [1-9] can be placed. If N is equal to 1, then 0 can be placed as well.
- For any other position, any digit from [0-9] can be placed.
- If a particular digit ‘i’ is included, then update mask as mask = mask | (1 << i ).
- After making a valid placement, recursively call the countOfNumbers function for index digit+1.
- Return the sum of all possible valid placements of digits as the answer.
Below is the implementation of the above approach:
Time Complexity: O(N2*210)
Auxiliary Space: O(N*210)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.