VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-array-element-having-maximum-frequency-of-the-digit-k/

⇱ Find the array element having maximum frequency of the digit K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the array element having maximum frequency of the digit K

Last Updated : 23 Jul, 2025

Given an arrayarr[] of size N and an integer K, the task is to find an array element that contains the digit K a maximum number of times. If more than one solutions exist, then print any one of them. Otherwise, print -1.

Examples:

Input: arr[] = {3, 77, 343, 456}, K = 3 
Output: 343 
Explanation:
Frequency of 3 in array elements: 1, 0, 2, 0 
343 has maximum frequency i.e. 2.

Input: arr[] = {1, 1111, 111, 11}, K = 1 
Output: 1111 
Explanation:
Frequency of 1 in array elements: 1, 4, 3, 2 
1111 has maximum frequency i.e. 4.

Approach: The idea is to traverse the array and for every individual array element, count the occurrences of the digit K in it. Follow the steps below to solve the problem:

  1. Initialize the max frequency of digit K, say maxfreq, as 0.
  2. Traverse the given array from the start element till the end.
  3. For every traversed element, find the frequency of digit K in that element. If it is greater than maxfreq, then update maxfreq and store that element.

Below is the implementation of the above approach:


Output
1111

Time Complexity: O(N * log10(N))
Auxiliary Space: O(1)

Another Approach:

  1. Start with an array arr[] of size N and an integer K.
  2. Initialize max_freq as 0 and result as -1.
  3. Traverse the array from the start to the end.
  4. For each element, count the number of occurrences of the digit K by iterating over its digits. You can do this by repeatedly dividing the number by 10 and checking the remainder for equality with K. If it's equal, increment a frequency counter.
  5. Compare the frequency counter with max_freq. If it's greater than max_freq, update max_freq with the frequency counter and result with the current element.
  6. After the traversal, if the max_freq is still 0, it means that no element contains the digit K, so return -1. Otherwise, return the result.
  7. Done.

Output
1111

Time Complexity: O(N*M)

Auxiliary Space: O(1)

Comment