20. Count Numbers Containing Specific Digits
β GFG solution to the Count Numbers Containing Specific Digits problem: find total n-digit numbers containing at least one digit from given array using complement counting technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an integer n
representing the number of digits in a number, and an array arr[]
containing digits from 0 to 9. Your task is to count how many n-digit positive integers can be formed such that at least one digit from the array arr[]
appears in the number.
An n-digit positive integer is a number that has exactly n digits and doesn't start with 0 (except when n=1, where single digit 0 is not considered a positive integer).
π Examples
Example 1
Input: n = 1, arr[] = [1, 2, 3]
Output: 3
Explanation: Only the single-digit numbers [1, 2, 3] satisfy the condition.
Example 2
Input: n = 2, arr[] = [3, 5]
Output: 34
Explanation: There are a total of 34 two-digit numbers which contain at least one out of [3, 5].
π Constraints
$1 \le n \le 9$
$1 \le \text{arr.size()} \le 10$
$0 \le \text{arr}[i] \le 9$
β
My Approach
The optimal approach uses Complement Counting technique with Bit Manipulation to efficiently calculate the result:
Complement Counting + Bit Manipulation
Core Insight:
Instead of directly counting numbers with at least one digit from
arr[]
, we count numbers with NO digits fromarr[]
and subtract from total.Formula:
Result = Total n-digit numbers - Numbers with forbidden digits only
Calculate Total n-digit Numbers:
For n=1: Total = 9 (digits 1-9, excluding 0)
For n>1: Total = 9 Γ 10^(n-1) (first digit: 1-9, remaining: 0-9)
Track Forbidden Digits:
Use bit manipulation to mark allowed digits from
arr[]
Count forbidden digits:
forbidden = 10 - |allowed_digits|
Count non-zero forbidden digits:
nonZeroForbidden = 9 - |allowed_nonzero_digits|
Calculate Invalid Numbers:
For n=1: Invalid = count of non-zero forbidden digits
For n>1: Invalid = nonZeroForbidden Γ forbidden^(n-1)
Final Result:
Return
Total - Invalid
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n + |arr|), where n is the number of digits and |arr| is the size of the input array. We iterate through the array once to mark allowed digits and perform n-1 multiplications for power calculation.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for bit masks and counting variables, regardless of input size.
π§βπ» Code (C++)
class Solution {
public:
int countValid(int n, vector<int>& arr) {
int mask = 0, nonZeroMask = 0;
for (int d : arr) {
mask |= (1 << d);
if (d) nonZeroMask |= (1 << d);
}
int forbidden = __builtin_popcount(~mask & 1023);
int nonZeroForbidden = __builtin_popcount(~nonZeroMask & 1022);
int total = 9, pow = 1;
for (int i = 1; i < n; i++) {
pow *= 10;
total *= 10;
}
int invalid = n == 1 ? nonZeroForbidden : nonZeroForbidden;
for (int i = 1; i < n; i++) invalid *= forbidden;
return total - invalid;
}
};
π§βπ» Code (Java)
class Solution {
public int countValid(int n, int[] arr) {
boolean[] allowed = new boolean[10];
for (int d : arr) allowed[d] = true;
int forbidden = 0, nonZeroForbidden = 0;
for (int i = 0; i < 10; i++) {
if (!allowed[i]) {
forbidden++;
if (i != 0) nonZeroForbidden++;
}
}
long total = 9;
for (int i = 1; i < n; i++) total *= 10;
long invalid = (n == 1) ? nonZeroForbidden : nonZeroForbidden;
for (int i = 1; i < n; i++) invalid *= forbidden;
return (int)(total - invalid);
}
}
π Code (Python)
class Solution:
def countValid(self, n, arr):
allowed = [False] * 10
for d in arr:
allowed[d] = True
forbidden = sum(1 for i in range(10) if not allowed[i])
non_zero_forbidden = sum(1 for i in range(1, 10) if not allowed[i])
total = 9 * (10 ** (n - 1))
invalid = non_zero_forbidden * (forbidden ** (n - 1)) if n > 1 else non_zero_forbidden
return total - invalid
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated