Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Problem Statement
3.
Efficient solutions and brute force
4.
Approach-1: Brute Force Approach 
5.
Implementation 
5.1.
C++
6.
Approach-2: Hashing
7.
Implementation
7.1.
C++
7.2.
Java
7.3.
Python
7.4.
Javascript
7.5.
C#
8.
Frequently Asked Questions
8.1.
How do you find the most common element in an array?
8.2.
What is the number that occurs the most frequently?
8.3.
In Python, how can I determine which elements are most frequent?
9.
Conclusion
Last Updated: May 7, 2024
Easy

Most frequent element in an array

Introduction

In this article, we will discuss the problem named to find the most frequent element in an array. Before jumping on to the approach to the problem, let us first understand the problem.

Problem Statement

Here we need to find the element that occurs the most frequently in the n-element size array Arry[], that is, the element that occurs the most frequently overall. There will always be at least one repeating element.

Example :

Input
Arry1[ ] = {1, 2, 4, 7, 2, 8}
Output
2

The maximum frequency in the Arry1 is 2, which appears two times.

Input
Arry2[ ] = {2, 3, 3, 2, 3, 4, 5}
Output
3

Here as you can see the maximum frequency in the Arry2 is 3, which appears three times in the given array.

Efficient solutions and brute force

In the below section, these possible solutions for resolving this problem will be discussed:

1. Using nested loops to calculate frequency using brute force.

2. Hash table usage to find the frequency of elements using a hash table.

 

Approach-1: Brute Force Approach 

In this approach we will find the repeated element by running two loops.

  •  First all elements are chosen one by one by the outer loop. 
  • The inner loop calculates the frequency of the chosen element. 
  • And then it compares it with the maximum value obtained so far.

Implementation 

  • C++

C++

#include <bits/stdc++.h>
using namespace std;
int mostFreqnt(int * arry, int n) {
 int max_count = 0;
 int maxfreqelement;
 for (int i = 0; i < n; i++) {
   int count = 0;
   for (int j = 0; j < n; j++) {
     if (arry[i] == arry[j])
       count++;
   }
   if (count > max_count) {
     max_count = count;
     maxfreqelement = arry[i];
   }
 }
 return maxfreqelement;
}
int main() {
 int arry[] = {4,5,3,4,5, 3,3 };
 int n = sizeof(arry) / sizeof(arry[0]);
 cout << mostFreqnt(arry, n);
 return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output : 

This solution has a time complexity of  O(n2) Since there are two loops that run from i=0 to i=n, omitting the numbers in a visited array for which we already know the frequency will decrease the time complexity.

Approach-2: Hashing

Use of hashing is an effective solution. As key-value pairs, we store elements and their frequency counts in a hash table. 

The hash table is then traversed, and the key with the maximum value is printed.

Now, let us quickly look at its Implementation: 

Implementation

  • C++
  • Java
  • Python
  • Javascript
  • C#

C++

#include <bits/stdc++.h>
using namespace std;

int mostFrequentelement(int arry[], int n) {
 // Inserting all the elements.
 unordered_map < int, int > hash;
 for (int i = 0; i < n; i++)
   hash[arry[i]]++;

 // finding max frequency
 int maxcount = 0, res = -1;
 for (auto i: hash) {
   if (maxcount < i.second) {
     res = i.first;
     maxcount = i.second;
   }
 }

 return res;
}

// driver program
int main() {
 int arry[] = {50,60,30,50,50,70,40};
 int n = sizeof(arry) / sizeof(arry[0]);
 cout << mostFrequentelement(arry, n);
 return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Java

import java.util.HashMap;
import java.util.Map;

public class Main {
static int mostFrequentelement(int[] arry) {
// Inserting all the elements.
Map<Integer, Integer> hash = new HashMap<>();
for (int i : arry)
hash.put(i, hash.getOrDefault(i, 0) + 1);

// finding max frequency
int maxcount = 0, res = -1;
for (Map.Entry<Integer, Integer> entry : hash.entrySet()) {
if (maxcount < entry.getValue()) {
res = entry.getKey();
maxcount = entry.getValue();
}
}

return res;
}

// driver program
public static void main(String[] args) {
int[] arry = {50, 60, 30, 50, 50, 70, 40};
System.out.println(mostFrequentelement(arry));
}
}
You can also try this code with Online Java Compiler
Run Code

Python

def mostFrequentelement(arry):
# Inserting all the elements.
hash = {}
for i in arry:
hash[i] = hash.get(i, 0) + 1

# finding max frequency
maxcount = 0
res = -1
for key, value in hash.items():
if maxcount < value:
res = key
maxcount = value

return res

# driver program
arry = [50, 60, 30, 50, 50, 70, 40]
print(mostFrequentelement(arry))
You can also try this code with Online Python Compiler
Run Code

Javascript

function mostFrequentelement(arry) {
// Inserting all the elements.
let hash = {};
arry.forEach(num => {
hash[num] = (hash[num] || 0) + 1;
});

// finding max frequency
let maxcount = 0;
let res = -1;
for (let key in hash) {
if (hash.hasOwnProperty(key) && maxcount < hash[key]) {
res = key;
maxcount = hash[key];
}
}

return res;
}

// driver program
let arry = [50, 60, 30, 50, 50, 70, 40];
console.log(mostFrequentelement(arry));
You can also try this code with Online Javascript Compiler
Run Code

C#

using System;
using System.Collections.Generic;

class MainClass {
static int mostFrequentelement(int[] arry) {
// Inserting all the elements.
Dictionary<int, int> hash = new Dictionary<int, int>();
foreach (int i in arry) {
if (hash.ContainsKey(i)) {
hash[i]++;
} else {
hash[i] = 1;
}
}

// finding max frequency
int maxcount = 0, res = -1;
foreach (KeyValuePair<int, int> pair in hash) {
if (maxcount < pair.Value) {
res = pair.Key;
maxcount = pair.Value;
}
}

return res;
}

// driver program
public static void Main(string[] args) {
int[] arry = {50, 60, 30, 50, 50, 70, 40};
Console.WriteLine(mostFrequentelement(arry));
}
}

Output : 

Frequently Asked Questions

How do you find the most common element in an array?

To find the most common element in an array, iterate through the array and keep track of the frequency of each element using a hash table or dictionary. Then, find the element with the highest frequency.

What is the number that occurs the most frequently?

The mode of a data set is the number that appears the most frequently. For instance, determine the mode of the numbers 2, 7, 13, and 2. While all the other numbers only appear once, the number 2 appears twice. Consequently, the answer is 2.

In Python, how can I determine which elements are most frequent?

Use Python Counter, which provides a count for each element in a list. So, using the most common() method, we can easily identify the element that is used the most.

Conclusion

In this article, we have discussed a simple and hashmap approach to find the most frequent element in an array. We hope that this article has helped you enhance your knowledge on finding the frequent elements. If you would like to learn more, check out our articles on arraysintroduction-to-hashingsort-the-given-array-after-sorting-each-number-individually and many more.

Check out the following problems - 

 

 

Refer to our guided path on code360 to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available, Take a look at the interview experiences and interview bundle for placement preparations.

Live masterclass