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:
- Initialize the max frequency of digit K, say maxfreq, as 0.
- Traverse the given array from the start element till the end.
- 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:
Time Complexity: O(N * log10(N))
Auxiliary Space: O(1)
Another Approach:
- Start with an array arr[] of size N and an integer K.
- Initialize max_freq as 0 and result as -1.
- Traverse the array from the start to the end.
- 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.
- 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.
- 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.
- Done.
Time Complexity: O(N*M)
Auxiliary Space: O(1)