Open In App

Most frequent element in an array

Last Updated : 26 Jul, 2025
Comments
Improve
Suggest changes
85 Likes
Like
Report

Given an integer array arr[], find the element that appears most frequently. If multiple elements have the same highest frequency, return the largest among 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 appears four times in array which is maximum frequency

Input: arr[] = [1, 2, 2, 4, 1]
Output: 2
Explanation: 1 and 2 both appear two times, so return 2 as it's value is bigger.

[Naive Approach] Nested Loops - O(n2) Time and O(1) Space

The naive approach involves using two nested loops: the outer loop picks each element, and the inner loop counts the frequency of the picked element. Update if count is higher than current max count or same but value is larger than current value.

C++
Java Python C# JavaScript

Output
30

[Better Approach] Using Sorting - O(n × log n) Time and O(1) Space

This approach begins by sorting the array, which groups identical elements together. Once sorted, a linear traversal is performed to count the frequency of each element. Since identical elements appear consecutively after sorting, tracking their frequency becomes straightforward.

C++
Java Python C# JavaScript

Output
30

[Expected Approach] Using Hashing - O(n) Time and O(n) Space

This approach uses a hash table to count the frequency of each element efficiently. After building the frequency map, the element with the highest frequency is identified and choosing the largest one in case of a tie.

C++
Java Python C# JavaScript

Output
30

Article Tags :

Explore