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++)
π§βπ» Code (Java)
π Code (Python)
π§ 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