Most frequent element in an array
Last Updated :
11 Jan, 2023
Given an array, find the most frequent element in it. If there are multiple elements that appear a maximum number of times, print any one of them.
Examples:
Input : arr[] = {1, 3, 2, 1, 4, 1}
Output : 1
Explanation: 1 appears three times in array which is maximum frequency.
Input : arr[] = {10, 20, 10, 20, 30, 20, 20}
Output : 20
A simple solution is to run two loops. The outer loop picks all elements one by one. The inner loop finds the frequency of the picked element and compares it with the maximum so far.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int mostFrequent( int * arr, int n)
{
int maxcount = 0;
int element_having_max_freq;
for ( int i = 0; i < n; i++) {
int count = 0;
for ( int j = 0; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
if (count > maxcount) {
maxcount = count;
element_having_max_freq = arr[i];
}
}
return element_having_max_freq;
}
int main()
{
int arr[] = { 40, 50, 30, 40, 50, 30, 30 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << mostFrequent(arr, n);
return 0;
}
|
Java
public class GFG
{
public static int mostFrequent( int [] arr, int n)
{
int maxcount = 0 ;
int element_having_max_freq = 0 ;
for ( int i = 0 ; i < n; i++) {
int count = 0 ;
for ( int j = 0 ; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > maxcount) {
maxcount = count;
element_having_max_freq = arr[i];
}
}
return element_having_max_freq;
}
public static void main(String[] args)
{
int [] arr = { 40 , 50 , 30 , 40 , 50 , 30 , 30 };
int n = arr.length;
System.out.print(mostFrequent(arr, n));
}
}
|
Python3
def mostFrequent(arr, n):
maxcount = 0 ;
element_having_max_freq = 0 ;
for i in range ( 0 , n):
count = 0
for j in range ( 0 , n):
if (arr[i] = = arr[j]):
count + = 1
if (count > maxcount):
maxcount = count
element_having_max_freq = arr[i]
return element_having_max_freq;
arr = [ 40 , 50 , 30 , 40 , 50 , 30 , 30 ]
n = len (arr)
print (mostFrequent(arr, n))
|
C#
using System;
public class GFG
{
public static int mostFrequent( int [] arr, int n)
{
int maxcount = 0;
int element_having_max_freq = 0;
for ( int i = 0; i < n; i++) {
int count = 0;
for ( int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > maxcount) {
maxcount = count;
element_having_max_freq = arr[i];
}
}
return element_having_max_freq;
}
public static void Main(String[] args)
{
int [] arr = { 40, 50, 30, 40, 50, 30, 30 };
int n = arr.Length;
Console.Write(mostFrequent(arr, n));
}
}
|
Javascript
function mostFrequent(arr, n) {
let maxcount = 0;
let element_having_max_freq;
for (let i = 0; i < n; i++) {
let count = 0;
for (let j = 0; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
if (count > maxcount) {
maxcount = count;
element_having_max_freq = arr[i];
}
}
return element_having_max_freq;
}
let arr = [40, 50, 30, 40, 50, 30, 30];
let n = arr.length;
console.log(mostFrequent(arr, n));
|
The time complexity of this solution is O(n2) since 2 loops are running from i=0 to i=n we can improve its time complexity by taking a visited array and skipping numbers for which we already calculated the frequency.
Auxiliary space: O(1) as it is using constant space for variables
A better solution is to do the sorting. We first sort the array, then linearly traverse the array.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int mostFrequent( int arr[], int n)
{
sort(arr, arr + n);
int max_count = 1, res = arr[0], curr_count = 1;
for ( int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1])
curr_count++;
else
curr_count = 1;
if (curr_count > max_count) {
max_count = curr_count;
res = arr[i - 1];
}
}
return res;
}
int main()
{
int arr[] = { 40,50,30,40,50,30,30};
int n = sizeof (arr) / sizeof (arr[0]);
cout << mostFrequent(arr, n);
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
int cmpfunc( const void * a, const void * b)
{
return (*( int *)a - *( int *)b);
}
int mostFrequent( int arr[], int n)
{
qsort (arr, n, sizeof ( int ), cmpfunc);
int max_count = 1, res = arr[0], curr_count = 1;
for ( int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1])
curr_count++;
else
curr_count = 1;
if (curr_count > max_count) {
max_count = curr_count;
res = arr[i - 1];
}
}
return res;
}
int main()
{
int arr[] = { 40,50,30,40,50,30,30};
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "%d" , mostFrequent(arr, n));
return 0;
}
|
Java
import java.util.*;
class GFG {
static int mostFrequent( int arr[], int n)
{
Arrays.sort(arr);
int max_count = 1 , res = arr[ 0 ];
int curr_count = 1 ;
for ( int i = 1 ; i < n; i++) {
if (arr[i] == arr[i - 1 ])
curr_count++;
else
curr_count = 1 ;
if (curr_count > max_count) {
max_count = curr_count;
res = arr[i - 1 ];
}
}
return res;
}
public static void main(String[] args)
{
int arr[] = { 40 , 50 , 30 , 40 , 50 , 30 , 30 };
int n = arr.length;
System.out.println(mostFrequent(arr, n));
}
}
|
Python3
def mostFrequent(arr, n):
arr.sort()
max_count = 1
res = arr[ 0 ]
curr_count = 1
for i in range ( 1 , n):
if (arr[i] = = arr[i - 1 ]):
curr_count + = 1
else :
curr_count = 1
if (curr_count > max_count):
max_count = curr_count
res = arr[i - 1 ]
return res
arr = [ 40 , 50 , 30 , 40 , 50 , 30 , 30 ]
n = len (arr)
print (mostFrequent(arr, n))
|
C#
using System;
class GFG {
static int mostFrequent( int [] arr, int n)
{
Array.Sort(arr);
int max_count = 1, res = arr[0];
int curr_count = 1;
for ( int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1])
curr_count++;
else
curr_count = 1;
if (curr_count > max_count) {
max_count = curr_count;
res = arr[i - 1];
}
}
return res;
}
public static void Main()
{
int [] arr = {40,50,30,40,50,30,30 };
int n = arr.Length;
Console.WriteLine(mostFrequent(arr, n));
}
}
|
PHP
<?php
function mostFrequent( $arr , $n )
{
sort( $arr );
sort( $arr , $n );
$max_count = 1;
$res = $arr [0];
$curr_count = 1;
for ( $i = 1; $i < $n ; $i ++)
{
if ( $arr [ $i ] == $arr [ $i - 1])
$curr_count ++;
else
$curr_count = 1;
if ( $curr_count > $max_count )
{
$max_count = $curr_count ;
$res = $arr [ $i - 1];
}
}
return $res ;
}
{
$arr = array (40,50,30,40,50,30,30);
$n = sizeof( $arr ) / sizeof( $arr [0]);
echo mostFrequent( $arr , $n );
return 0;
}
?>
|
Javascript
<script>
function mostFrequent(arr, n)
{
arr.sort();
let max_count = 1, res = arr[0];
let curr_count = 1;
for (let i = 1; i < n; i++)
{
if (arr[i] == arr[i - 1])
curr_count++;
else
curr_count = 1;
if (curr_count > max_count)
{
max_count = curr_count;
res = arr[i - 1];
}
}
return res;
}
let arr = [40,50,30,40,50,30,30];
let n = arr.length;
document.write(mostFrequent(arr,n));
</script>
|
Time Complexity: O(nlog(n))
Auxiliary Space: O(1)
An efficient solution is to use hashing. We create a hash table and store elements and their frequency counts as key-value pairs. Finally, we traverse the hash table and print the key with the maximum value.
C++
#include <bits/stdc++.h>
using namespace std;
int mostFrequent( int arr[], int n)
{
unordered_map< int , int > hash;
for ( int i = 0; i < n; i++)
hash[arr[i]]++;
int max_count = 0, res = -1;
for ( auto i : hash) {
if (max_count < i.second) {
res = i.first;
max_count = i.second;
}
}
return res;
}
int main()
{
int arr[] = {40,50,30,40,50,30,30 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << mostFrequent(arr, n);
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
class GFG {
static int mostFrequent( int arr[], int n)
{
Map<Integer, Integer> hp =
new HashMap<Integer, Integer>();
for ( int i = 0 ; i < n; i++)
{
int key = arr[i];
if (hp.containsKey(key))
{
int freq = hp.get(key);
freq++;
hp.put(key, freq);
}
else
{
hp.put(key, 1 );
}
}
int max_count = 0 , res = - 1 ;
for (Entry<Integer, Integer> val : hp.entrySet())
{
if (max_count < val.getValue())
{
res = val.getKey();
max_count = val.getValue();
}
}
return res;
}
public static void main (String[] args) {
int arr[] = { 40 , 50 , 30 , 40 , 50 , 30 , 30 };
int n = arr.length;
System.out.println(mostFrequent(arr, n));
}
}
|
Python3
import math as mt
def mostFrequent(arr, n):
Hash = dict ()
for i in range (n):
if arr[i] in Hash .keys():
Hash [arr[i]] + = 1
else :
Hash [arr[i]] = 1
max_count = 0
res = - 1
for i in Hash :
if (max_count < Hash [i]):
res = i
max_count = Hash [i]
return res
arr = [ 40 , 50 , 30 , 40 , 50 , 30 , 30 ]
n = len (arr)
print (mostFrequent(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int mostFrequent( int []arr,
int n)
{
Dictionary< int , int > hp =
new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
{
int key = arr[i];
if (hp.ContainsKey(key))
{
int freq = hp[key];
freq++;
hp[key] = freq;
}
else
hp.Add(key, 1);
}
int min_count = 0, res = -1;
foreach (KeyValuePair< int ,
int > pair in hp)
{
if (min_count < pair.Value)
{
res = pair.Key;
min_count = pair.Value;
}
}
return res;
}
static void Main ()
{
int []arr = new int []{40,50,30,40,50,30,30};
int n = arr.Length;
Console.Write(mostFrequent(arr, n));
}
}
|
Javascript
<script>
function mostFrequent(arr, n)
{
var hash = new Map();
for ( var i = 0; i < n; i++)
{
if (hash.has(arr[i]))
hash.set(arr[i], hash.get(arr[i])+1)
else
hash.set(arr[i], 1)
}
var max_count = 0, res = -1;
hash.forEach((value,key) => {
if (max_count < value) {
res = key;
max_count = value;
}
});
return res;
}
var arr = [40,50,30,40,50,30,30];
var n = arr.length;
document.write( mostFrequent(arr, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
An efficient solution to this problem can be to solve this problem by Moore’s voting Algorithm.
NOTE: THE ABOVE VOTING ALGORITHM ONLY WORKS WHEN THE MAXIMUM OCCURRING ELEMENT IS MORE THAN (SIZEOFARRAY/2) TIMES;
In this method, we will find the maximum occurred integer by counting the votes a number has.
C++
#include <iostream>
using namespace std;
int maxFreq( int *arr, int n) {
int res = 0;
int count = 1;
for ( int i = 1; i < n; i++) {
if (arr[i] == arr[res]) {
count++;
} else {
count--;
}
if (count == 0) {
res = i;
count = 1;
}
}
return arr[res];
}
int main()
{
int arr[] = {40,50,30,40,50,30,30};
int n = sizeof (arr) / sizeof (arr[0]);
int freq = maxFreq(arr , n);
int count = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] == freq) {
count++;
}
}
cout << "Element " << maxFreq(arr , n) << " occurs " << count << " times" << endl;;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int maxFreq( int []arr, int n)
{
int res = 0 ;
int count = 1 ;
for ( int i = 1 ; i < n; i++) {
if (arr[i] == arr[res]) {
count++;
} else {
count--;
}
if (count == 0 ) {
res = i;
count = 1 ;
}
}
return arr[res];
}
public static void main (String[] args) {
int arr[] = { 40 , 50 , 30 , 40 , 50 , 30 , 30 };
int n = arr.length;
int freq = maxFreq(arr , n);
int count = 0 ;
for ( int i = 0 ; i < n; i++) {
if (arr[i] == freq) {
count++;
}
}
System.out.println( "Element " +maxFreq(arr , n) + " occurs " +count + " times" );
}
}
|
Python3
def maxFreq(arr, n):
res = 0
count = 1
for i in range ( 1 , n):
if (arr[i] = = arr[res]):
count + = 1
else :
count - = 1
if (count = = 0 ):
res = i
count = 1
return arr[res]
arr = [ 40 , 50 , 30 , 40 , 50 , 30 , 30 ]
n = len (arr)
freq = maxFreq(arr, n)
count = 0
for i in range (n):
if (arr[i] = = freq):
count + = 1
print ( "Element " , maxFreq(arr , n),
" occurs " , count, " times" )
|
C#
using System;
class GFG
{
static int maxFreq( int []arr, int n)
{
int res = 0;
int count = 1;
for ( int i = 1; i < n; i++) {
if (arr[i] == arr[res]) {
count++;
} else {
count--;
}
if (count == 0) {
res = i;
count = 1;
}
}
return arr[res];
}
public static void Main (String[] args) {
int []arr = {40,50,30,40,50,30,30};
int n = arr.Length;
int freq = maxFreq(arr , n);
int count = 0;
for ( int i = 0; i < n; i++) {
if (arr[i] == freq) {
count++;
}
}
Console.Write( "Element " +maxFreq(arr , n) + " occurs " +count + " times" );
}
}
|
Javascript
<script>
function maxFreq(arr, n) {
var res = 0;
var count = 1;
for ( var i = 1; i < n; i++) {
if (arr[i] === arr[res]) {
count++;
} else {
count--;
}
if (count === 0) {
res = i;
count = 1;
}
}
return arr[res];
}
var arr = [40, 50, 30, 40, 50, 30, 30];
var n = arr.length;
var freq = maxFreq(arr, n);
var count = 0;
for ( var i = 0; i < n; i++) {
if (arr[i] === freq) {
count++;
}
}
document.write(
"Element " + maxFreq(arr, n) + " occurs " +
count + " times" + "<br>"
);
</script>
|
Output
Element 30 occurs 3 times
Time Complexity: O(n)
Auxiliary Space: O(1)
Please Login to comment...