Find the element which appears maximum number of times in the array.

Objective: Given an array of integers, write a algorithm to find the element which appears maximum number of times in the array.

Example:

int [] arrA = {4, 1, 5, 2, 1, 5, 9, 8, 6, 5, 3, 2, 4, 7};
Output: Element repeating maximum no of times: 5, maximum count: 3

Approach:

Naive approach: Use 2 loops. Check each element in the array with all other elements in the array and keep track of its count and also maintain the max counter which track the element repeats the maximum number of time.

Time Complexity : O(n^2) Space Complexity: O(1)

Code:

 

Sorting approach: Sort the array, this will bring all the duplicates together if present. Now navigate the array and keep track of its count and also maintain the max counter which track the element repeats the maximum number of time.

Time Complexity : O(nlogn) Space Complexity: O(n) by using merge sort.

Code:

 

Better Solution : Use Hashmap. Store the count of each element of array in a hash table and later check in Hash map which element has the maximum count – Find duplicates in an given array

Time Complexity : O(n) and Space Complexity: O(n).

Code:

 

Better Solution (Conditional) : O(n) time and O(1) extra space.

  • This solution works only if array has positive integers and all the elements in the array are in range from 0 to n-1 where n is the size of the array.
  • Nav­i­gate the array.
  • Update the array as for ith index :- arrA[arrA[i]% n] = arrA[arrA[i]% n] + n;
  • Now navigate the updated array and check which index has the maximum value, that index number is the element which has the maximum occurrence in the array.
  • See the picture below for more explanation.

 

Similar approach used in problem : if array has all consecutive numbers.

Code:

Output:

Element repeating maximum no of times: 5, maximum count: 3

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

  • Lê Khoa

    Buggy code, please change arr to {4, 1, 7, 2, 7, 5, 9, 8, 6, 1, 7, 2, 4, 7};; and see the result.

    • tutorialhorizon

      Thanks Le, corrected it

  • Lê Khoa

    Actually the line: arrA[index] = arrA[index] + size; has problem, please check … it is serious mistake

    • tutorialhorizon

      Thanks Le, the problem was in printing the result. It was “arrA[maxIndex]%size” , changed it to “maxIndex”. Please let us know if you find issues in this or any other posts.

      • Lê Khoa

        Hi tutorial, it’s fine now. U are right, just the output is not correct as expected. Thanks for your powerful articles !

%d bloggers like this: