![]() |
VOOZH | about |
Given an array arr[]. The array contains numbers ranging from 0 to k-1 where k is a positive integer. Find the maximum repeating number in this array. If there are two or more maximum repeating numbers, return the element with the least value.
Input: k = 3, arr[] = [2, 2, 1, 2]
Output: 2
Explanation: 2 is the most frequent element.Input: k = 3, arr[] = [2, 2, 1, 0, 0, 1]
Output: 0
Explanation: 0, 1, and 2 all have the same frequency of 2. But since 0 is the smallest, you need to return 0.
Table of Content
We check the frequency of each element by comparing it with every other element. The element with the highest frequency is selected, and in case of a tie, the smaller element is chosen.
3
Since elements lie in range
0 to k-1, we can directly use a frequency array of sizekto count occurrences. Then we scan this array to find the element with maximum frequency, choosing the smallest element in case of a tie.
k initialized with 0 maxFreq = 0 and result = 00 to k-1maxFreq and result10
Exercise: The above solution prints only one repeating element and doesn't work if we want to print all maximum repeating elements. For example, if the input array is {2, 3, 2, 3}, the above solution will print only 3. What if we need to print both of 2 and 3 as both of them occur maximum number of times. Write a O(n) time and O(1) extra space function that prints all maximum repeating elements. (Hint: We can use maximum quotient arr[i]/n instead of maximum value in step 2).
Note that the above solutions may cause overflow if adding k repeatedly makes the value more than INT_MAX.