Given an array of n integers, find the most frequent element in it i.e., the element that occurs the maximum number of times. If there are multiple elements that appear a maximum number of times, find the smallest of them.
Please note that this section might seem a bit difficult without prior knowledge on what hashing is, we will soon try to add basics concepts for your ease! If you know the concepts already please go ahead to give a shot to the problem. Cheers!
Input: arr = [1, 2, 2, 3, 3, 3]
Output: 3
Explanation: The number 3 appears the most (3 times). It is the most frequent element.
Input: arr = [4, 4, 5, 5, 6]
Output: 4
Explanation: Both 4 and 5 appear twice, but 4 is smaller. So, 4 is the most frequent element.
Input: arr = [10, 9 ,7]
A brute-force way to solve this problem will be to use two loops:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to get the highest
occurring element in array nums */
int mostFrequentElement(vector<int> &nums) {
// Variable to store the size of array
int n = nums.size();
// Variable to store maximum frequency
int maxFreq = 0;
/* Variable to store element
with maximum frequency */
int maxEle;
// Visited array
vector<bool> visited(n, false);
// First loop
for(int i = 0; i < n; i++) {
// Skip second loop if already visited
if(visited[i]) continue;
/* Variable to store frequency
of current element */
int freq = 0;
// Second loop
for(int j = i; j < n; j++) {
if(nums[i] == nums[j]) {
freq++;
visited[j] = true;
}
}
/* Update variables if new element having
highest frequency is found */
if(freq > maxFreq) {
maxFreq = freq;
maxEle = nums[i];
} else if(freq == maxFreq) {
maxEle = min(maxEle, nums[i]);
}
}
// Return the result
return maxEle;
}
};
int main() {
vector<int> nums = {4, 4, 5, 5, 6};
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to get the
highest occurring element in array nums */
int ans = sol.mostFrequentElement(nums);
cout << "The highest occurring element in the array is: " << ans;
return 0;
}
import java.util.*;
class Solution {
/* Function to get the highest
occurring element in array nums */
public int mostFrequentElement(int[] nums) {
// Variable to store the size of array
int n = nums.length;
// Variable to store maximum frequency
int maxFreq = 0;
/* Variable to store element
with maximum frequency */
int maxEle = 0;
// Visited array
boolean[] visited = new boolean[n];
// First loop
for (int i = 0; i < n; i++) {
// Skip second loop if already visited
if (visited[i]) continue;
/* Variable to store frequency
of current element */
int freq = 0;
// Second loop
for (int j = i; j < n; j++) {
if (nums[i] == nums[j]) {
freq++;
visited[j] = true;
}
}
/* Update variables if new element having
highest frequency is found */
if (freq > maxFreq) {
maxFreq = freq;
maxEle = nums[i];
} else if (freq == maxFreq) {
maxEle = Math.min(maxEle, nums[i]);
}
}
// Return the result
return maxEle;
}
public static void main(String[] args) {
int[] nums = {4, 4, 5, 5, 6};
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to get the
highest occurring element in array nums */
int ans = sol.mostFrequentElement(nums);
System.out.println("The highest occurring element in the array is: " + ans);
}
}
class Solution:
# Function to get the highest
# occurring element in array nums
def mostFrequentElement(self, nums):
# Variable to store the size of array
n = len(nums)
# Variable to store maximum frequency
maxFreq = 0
# Variable to store element
# with maximum frequency
maxEle = 0
# Visited array
visited = [False] * n
# First loop
for i in range(n):
# Skip second loop if already visited
if visited[i]:
continue
# Variable to store frequency
# of current element
freq = 0
# Second loop
for j in range(i, n):
if nums[i] == nums[j]:
freq += 1
visited[j] = True
# Update variables if new element having
# highest frequency is found
if freq > maxFreq:
maxFreq = freq
maxEle = nums[i]
elif freq == maxFreq:
maxEle = min(maxEle, nums[i])
# Return the result
return maxEle
if __name__ == "__main__":
nums = [4, 4, 5, 5, 6]
# Creating an instance of Solution class
sol = Solution()
# Function call to get the
# highest occurring element in array nums
ans = sol.mostFrequentElement(nums)
print("The highest occurring element in the array is:", ans)
class Solution {
/* Function to get the highest
occurring element in array nums */
mostFrequentElement(nums) {
// Variable to store the size of array
let n = nums.length;
// Variable to store maximum frequency
let maxFreq = 0;
/* Variable to store element
with maximum frequency */
let maxEle = 0;
// Visited array
let visited = new Array(n).fill(false);
// First loop
for (let i = 0; i < n; i++) {
// Skip second loop if already visited
if (visited[i]) continue;
/* Variable to store frequency
of current element */
let freq = 0;
// Second loop
for (let j = i; j < n; j++) {
if (nums[i] == nums[j]) {
freq++;
visited[j] = true;
}
}
/* Update variables if new element having
highest frequency is found */
if (freq > maxFreq) {
maxFreq = freq;
maxEle = nums[i];
} else if (freq == maxFreq) {
maxEle = Math.min(maxEle, nums[i]);
}
}
// Return the result
return maxEle;
}
}
// Input array
let nums = [4, 4, 5, 5, 6];
// Creating an instance of Solution class
let sol = new Solution();
/* Function call to get the
highest occurring element in array nums */
let ans = sol.mostFrequentElement(nums);
console.log("The highest occurring element in the array is: " + ans);
Time Complexity: O(N2) (where N is the size of the array given) – Using two nested loops.
Space Complexity: O(N) – Using a visited array of size N and a couple of variables.
An optimal approach to solve this question will be to use a Hashmap, a data structure that stores key-value pairs.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to get the highest
occuring element in array n */
int mostFrequentElement(vector<int> &nums) {
// Variable to store the size of array
int n = nums.size();
// Variable to store maximum frequency
int maxFreq = 0;
/* Variable to store element
with maximum frequency */
int maxEle;
// HashMap
unordered_map<int, int> mpp;
// Iterating on the array
for (int i = 0; i < n; i++) {
// Updating hashmap
mpp[nums[i]]++;
}
// Iterate on the map
for(auto it : mpp) {
int ele = it.first; // Key
int freq = it.second; // Value
if(freq > maxFreq) {
maxFreq = freq;
maxEle = ele;
}
else if(freq == maxFreq) {
maxEle = min(maxEle, ele);
}
}
// Return the result
return maxEle;
}
};
int main() {
vector<int> nums = {4, 4, 5, 5, 6};
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to get the
highest occuring element in array n */
int ans = sol.mostFrequentElement(nums);
cout << "The highest occurring element in the array is: " << ans;
return 0;
}
import java.util.*;
class Solution {
/* Function to get the highest
occurring element in array n */
public int mostFrequentElement(int[] nums) {
// Variable to store the size of array
int n = nums.length;
// Variable to store maximum frequency
int maxFreq = 0;
/* Variable to store element
with maximum frequency */
int maxEle = 0;
// HashMap
Map<Integer, Integer> mpp = new HashMap<>();
// Iterating on the array
for (int i = 0; i < n; i++) {
// Updating hashmap
mpp.put(nums[i], mpp.getOrDefault(nums[i], 0) + 1);
}
// Iterate on the map
for (Map.Entry<Integer, Integer> it : mpp.entrySet()) {
int ele = it.getKey(); // Key
int freq = it.getValue(); // Value
if (freq > maxFreq) {
maxFreq = freq;
maxEle = ele;
} else if (freq == maxFreq) {
maxEle = Math.min(maxEle, ele);
}
}
// Return the result
return maxEle;
}
public static void main(String[] args) {
int[] nums = {4, 4, 5, 5, 6};
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to get the
highest occurring element in array n */
int ans = sol.mostFrequentElement(nums);
System.out.println("The highest occurring element in the array is: " + ans);
}
}
class Solution:
# Function to get the highest
# occurring element in array n
def mostFrequentElement(self, nums):
# Variable to store the size of array
n = len(nums)
# Variable to store maximum frequency
maxFreq = 0
# Variable to store element
# with maximum frequency
maxEle = 0
# HashMap
mpp = {}
# Iterating on the array
for num in nums:
# Updating hashmap
if num in mpp:
mpp[num] += 1
else:
mpp[num] = 1
# Iterate on the map
for ele, freq in mpp.items():
if freq > maxFreq:
maxFreq = freq
maxEle = ele
elif freq == maxFreq:
maxEle = min(maxEle, ele)
# Return the result
return maxEle
# Input array
nums = [4, 4, 5, 5, 6]
# Creating an instance of Solution class
sol = Solution()
# Function call to get the highest
# occurring element in array n
ans = sol.mostFrequentElement(nums)
print(f"The highest occurring element in the array is: {ans}")
class Solution {
/* Function to get the highest
occurring element in array n */
mostFrequentElement(nums) {
// Variable to store the size of array
let n = nums.length;
// Variable to store maximum frequency
let maxFreq = 0;
// Variable to store element
// with maximum frequency
let maxEle = 0;
// HashMap
let mpp = new Map();
// Iterating on the array
for (let i = 0; i < n; i++) {
// Updating hashmap
mpp.set(nums[i], (mpp.get(nums[i]) || 0) + 1);
}
// Iterate on the map
for (let [ele, freq] of mpp) {
if (freq > maxFreq) {
maxFreq = freq;
maxEle = ele;
} else if (freq === maxFreq) {
maxEle = Math.min(maxEle, ele);
}
}
// Return the result
return maxEle;
}
}
// Input array
let nums = [4, 4, 5, 5, 6];
/* Creating an instance of
Solution class */
let sol = new Solution();
/* Function call to get the
highest occurring element in array n */
let ans = sol.mostFrequentElement(nums);
console.log(`The highest occurring element in the array is: ${ans}`);
Time Complexity: O(N) (where N is the size of the array given) –
Space Complexity: O(N) – In the worst-case scenario, the HashMap will store all the elements in the array when array elements are unique.