VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-array-elements-whose-all-distinct-digits-appear-in-k/

⇱ Count array elements whose all distinct digits appear in K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count array elements whose all distinct digits appear in K

Last Updated : 23 Jul, 2025

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:


Output: 
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:

  • Iterate over the digits of K and insert all the digits into a HashSet say set
  • Traverse the array arr[] and for every array element, iterate over all the digits of the current element and check if all the digits are present in the set or not. If found to be true, then increment the count.
  • Finally, print the count obtained.

Below is the implementation of the above approach:


Output: 
4

 

Time Complexity: O(N * log10(Max)), where Max is the largest array element 
Auxiliary Space: O(1)

Comment
Article Tags: