VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-maximum-repeating-number-in-ok-time/

⇱ Max Repeating in a Limited Range Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Max Repeating in a Limited Range Array

Last Updated : 3 May, 2026

Given an array arr[]. The array contains numbers ranging from 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.

[Naive Approach] Two Nested Loops- O(n²) Time and O(1) Space

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.


Output
3

[Better Approach] Using Frequency Array - O(n + k) Time and O(k) Space

Since elements lie in range 0 to k-1, we can directly use a frequency array of size k to count occurrences. Then we scan this array to find the element with maximum frequency, choosing the smallest element in case of a tie.

  • Create a frequency array of size k initialized with 0
  • Traverse the input array and increment frequency of each element
  • Initialize maxFreq = 0 and result = 0
  • Traverse frequency array from 0 to k-1
  • If current frequency is greater, update maxFreq and result
  • If frequency is equal, choose the smaller index

Output
10

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.  

Comment
Article Tags:
Article Tags: