Write a java program to find and print the most repeated element in the array in O(n). If there is more than one number having the same highest frequency, then print the smaller value.


To find the number which has the highest frequency, we have to follow the following steps.

  1. Sort the array in Ascending Order.
  2. Loop through the array and count the frequency of each element.
  3. Check for each number if thier frequency is greater than the old max frequency.
  4. If yes then update the max frequency and note the number.
  5. Repeat the steps for all distinct elements.
  6. Output the the number which has highest frequency or repeated most times in the array.

Initially, the max frequency will be Integer.MIN_VALUE, which stores the minimum available integer supported by the machine.

We have sorted the array because the same elements will come together; hence, it will be easier to count the frequency of each element in O(n).

So, overall we are trying to do the following as depicted in the image.

solving max repeated element in array

Let’s do the same in Java.

Output- 4:3

Time Complexity – O(n)
Space Complexity – O(1)

There are other several ways to find the most repeated element or the element with the highest frequency. I have only mentioned which is efficient and best for programming.

If you have any doubts or suggestions, then comment below.

Leave a Reply

Close Menu