![]() |
VOOZH | about |
Given an array arr[] consisting of N positive integers and a positive integer K, the task is to find the count of array elements whose distinct digits are a subset of the digits of K.
Examples:
Input: arr[] = { 1, 12, 1222, 13, 2 }, K = 12
Output: 4
Explanation:
Distinct Digits of K are { 1, 2 }
Distinct Digits of arr[0] are { 1 }, which is the subset of the digits of K.
Distinct Digits of arr[1] are { 1, 2 }, which is the subset of the digits of K.
Distinct Digits of arr[2] are { 1, 2 }, which is the subset of the digits of K.
Distinct Digits of arr[3] are { 1, 3 }, which is not the subset of the digits of K.
Distinct Digits of arr[4] are { 2 }, which is the subset of the digits of K.
Therefore, the required output is 4.Input: arr = {1, 2, 3, 4, 1234}, K = 1234
Output: 5
Naive Approach: The simplest approach to solve the problem is to traverse the array arr[] and for each array element, check if all its distinct digits appear in K or not. If found to be true, then increment the count. Finally, print the count obtained.
Below is the implementation of the above approach:
4
Time Complexity: O(N * log10(K) * log10(Max)), Max is the largest array element
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using a HashSet. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
4
Time Complexity: O(N * log10(Max)), where Max is the largest array element
Auxiliary Space: O(1)