Open In App

Most frequent element in an array

Last Updated : 07 Jul, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
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(n^2) 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++
#include <iostream>
#include <vector>

using namespace std;

int mostFreqEle(vector<int> &arr) {
    
    int n = arr.size(), maxcount = 0;
    int res;
    
    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 is greater or if count 
        // is same but value is bigger.
        if (count > maxcount || (count == maxcount && arr[i] > res)) {
            maxcount = count;
            res = arr[i];
        }
    }

    return res;
}

int main() {
    vector<int> arr = { 40, 50, 30, 40, 50, 30, 30 };
    cout << mostFreqEle(arr);
    return 0;
}
Java
class GfG {
    static int mostFreqEle(int[] arr) {
        int n = arr.length, maxcount = 0;
        int res = 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 is greater or if count 
            // is same but value is bigger.
            if (count > maxcount || (count == maxcount && arr[i] > res)) {
                maxcount = count;
                res = arr[i];
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = { 40, 50, 30, 40, 50, 30, 30 };
        System.out.println(mostFreqEle(arr));
    }
}
Python
def mostFreqEle(arr):
    n = len(arr)
    maxcount = 0
    res = 0
    
    for i in range(n):
        count = 0
        for j in range(n):
            if arr[i] == arr[j]:
                count += 1
        
        # If count is greater or if count 
        # is same but value is bigger.
        if count > maxcount or (count == maxcount and arr[i] > res):
            maxcount = count
            res = arr[i]

    return res

if __name__ == "__main__":
    arr = [40, 50, 30, 40, 50, 30, 30]
    print(mostFreqEle(arr))
C#
using System;

class GfG {
    
    static int mostFreqEle(int[] arr) {
        int n = arr.Length, maxcount = 0;
        int res = 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 is greater or if count 
            // is same but value is bigger.
            if (count > maxcount || (count == maxcount && arr[i] > res)) {
                maxcount = count;
                res = arr[i];
            }
        }

        return res;
    }

    static void Main() {
        int[] arr = { 40, 50, 30, 40, 50, 30, 30 };
        Console.WriteLine(mostFreqEle(arr));
    }
}
JavaScript
function mostFreqEle(arr) {
    let n = arr.length, maxcount = 0;
    let res = 0;
    
    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 is greater or if count 
        // is same but value is bigger.
        if (count > maxcount || (count === maxcount && arr[i] > res)) {
            maxcount = count;
            res = arr[i];
        }
    }

    return res;
}

// Driver Code
let arr = [40, 50, 30, 40, 50, 30, 30];
console.log(mostFreqEle(arr));

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++
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int mostFreqEle(vector<int>& arr) {
    
    // Sort the array
    sort(arr.begin(), arr.end());

    int maxCnt = 1, res = arr[0], currCnt = 1;
    for (int i = 1; i < arr.size(); i++) {
        
        // previous element if equal to current element 
        if (arr[i] == arr[i - 1])
            currCnt++;
        else
            currCnt = 1;
        
        // Update if curr count is higher or same but value is larger
        if (currCnt > maxCnt || (currCnt == maxCnt && arr[i] > res)) {
            maxCnt = currCnt;
            res = arr[i];
        }
    }

    return res;
}

int main() {
    vector<int> arr = { 40, 50, 30, 40, 50, 30, 30 };
    cout << mostFreqEle(arr);
    return 0;
}
Java
import java.util.Arrays;

class GfG {
    static int mostFreqEle(int[] arr) {
        
        // Sort the array
        Arrays.sort(arr);

        int maxCnt = 1, res = arr[0], currCnt = 1;
        for (int i = 1; i < arr.length; i++) {
            
            // previous element if equal to current element 
            if (arr[i] == arr[i - 1])
                currCnt++;
            else
                currCnt = 1;
            
            // Update if curr count is higher or same but value is larger
            if (currCnt > maxCnt || (currCnt == maxCnt && arr[i] > res)) {
                maxCnt = currCnt;
                res = arr[i];
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = { 40, 50, 30, 40, 50, 30, 30 };
        System.out.println(mostFreqEle(arr));
    }
}
Python
def mostFreqEle(arr):
    
    # Sort the array
    arr.sort()

    maxCnt, res, currCnt = 1, arr[0], 1
    for i in range(1, len(arr)):
        
        # previous element if equal to current element 
        if arr[i] == arr[i - 1]:
            currCnt += 1
        else:
            currCnt = 1
        
        # Update if curr count is higher or same but value is larger
        if currCnt > maxCnt or (currCnt == maxCnt and arr[i] > res):
            maxCnt = currCnt
            res = arr[i]

    return res

if __name__ == "__main__":
    arr = [40, 50, 30, 40, 50, 30, 30]
    print(mostFreqEle(arr))
C#
using System;

class GfG {
    static int mostFreqEle(int[] arr) {
        
        // Sort the array
        Array.Sort(arr);

        int maxCnt = 1, res = arr[0], currCnt = 1;
        for (int i = 1; i < arr.Length; i++) {
            
            // previous element if equal to current element 
            if (arr[i] == arr[i - 1])
                currCnt++;
            else
                currCnt = 1;
            
            // Update if curr count is higher or same but value is larger
            if (currCnt > maxCnt || (currCnt == maxCnt && arr[i] > res)) {
                maxCnt = currCnt;
                res = arr[i];
            }
        }

        return res;
    }

    static void Main() {
        int[] arr = { 40, 50, 30, 40, 50, 30, 30 };
        Console.WriteLine(mostFreqEle(arr));
    }
}
JavaScript
function mostFreqEle(arr) {
    
    // Sort the array
    arr.sort((a, b) => a - b);

    let maxCnt = 1, res = arr[0], currCnt = 1;
    for (let i = 1; i < arr.length; i++) {
        
        // previous element if equal to current element 
        if (arr[i] === arr[i - 1])
            currCnt++;
        else
            currCnt = 1;
        
        // Update if curr count is higher or same but value is larger
        if (currCnt > maxCnt || (currCnt === maxCnt && arr[i] > res)) {
            maxCnt = currCnt;
            res = arr[i];
        }
    }

    return res;
}

// Driver Code
let arr = [40, 50, 30, 40, 50, 30, 30];
console.log(mostFreqEle(arr));

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++
#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

int mostFreqEle(vector<int>& arr) {
    int n = arr.size();
    
    // Insert all elements in hash map.
    unordered_map<int, int> freq;
    for (int i = 0; i < n; i++)
        freq[arr[i]]++;

    // find the max frequency
    int maxCnt = 0, res = -1;
    for (auto i : freq) {
        int val = i.first, cnt = i.second;
        
        // Update if frequency is higher or same but value is larger
        if (maxCnt < cnt || (cnt == maxCnt && val > res)) {
            res = val;
            maxCnt = cnt;
        }
    }

    return res;
}

int main() {
    vector<int> arr = { 40, 50, 30, 40, 50, 30, 30 };
    cout << mostFreqEle(arr);
    return 0;
}
Java
import java.util.HashMap;

class GfG {
    static int mostFreqEle(int[] arr) {
        int n = arr.length;
        
        // Insert all elements in hash map.
        HashMap<Integer, Integer> freq = new HashMap<>();
        for (int i = 0; i < n; i++)
            freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1);

        // find the max frequency
        int maxCnt = 0, res = -1;
        for (var entry : freq.entrySet()) {
            int val = entry.getKey(), cnt = entry.getValue();
            
            // Update if frequency is higher or same but value is larger
            if (maxCnt < cnt || (cnt == maxCnt && val > res)) {
                res = val;
                maxCnt = cnt;
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] arr = { 40, 50, 30, 40, 50, 30, 30 };
        System.out.println(mostFreqEle(arr));
    }
}
Python
def mostFreqEle(arr):
    n = len(arr)
    
    # Insert all elements in hash map.
    freq = {}
    for i in range(n):
        freq[arr[i]] = freq.get(arr[i], 0) + 1

    # find the max frequency
    maxCnt, res = 0, -1
    for val, cnt in freq.items():
        
        # Update if frequency is higher or same but value is larger
        if maxCnt < cnt or (cnt == maxCnt and val > res):
            res = val
            maxCnt = cnt

    return res

if __name__ == "__main__":
    arr = [40, 50, 30, 40, 50, 30, 30]
    print(mostFreqEle(arr))
C#
using System;
using System.Collections.Generic;

class GfG {

    static int mostFreqEle(int[] arr) {
        int n = arr.Length;
        
        // Insert all elements in hash map.
        Dictionary<int, int> freq = new Dictionary<int, int>();
        for (int i = 0; i < n; i++)
            freq[arr[i]] = freq.ContainsKey(arr[i]) ? freq[arr[i]] + 1 : 1;

        // find the max frequency
        int maxCnt = 0, res = -1;
        foreach (var entry in freq) {
            int val = entry.Key, cnt = entry.Value;
            
            // Update if frequency is higher or same but value is larger
            if (maxCnt < cnt || (cnt == maxCnt && val > res)) {
                res = val;
                maxCnt = cnt;
            }
        }

        return res;
    }

    static void Main() {
        int[] arr = { 40, 50, 30, 40, 50, 30, 30 };
        Console.WriteLine(mostFreqEle(arr));
    }
}
JavaScript
function mostFreqEle(arr) {
    let n = arr.length;
    
    // Insert all elements in hash map.
    let freq = new Map();
    for (let i = 0; i < n; i++)
        freq.set(arr[i], (freq.get(arr[i]) || 0) + 1);

    // find the max frequency
    let maxCnt = 0, res = -1;
    for (let [val, cnt] of freq) {
        
        // Update if frequency is higher or same but value is larger
        if (maxCnt < cnt || (cnt === maxCnt && val > res)) {
            res = val;
            maxCnt = cnt;
        }
    }

    return res;
}

// Driver Code
let arr = [40, 50, 30, 40, 50, 30, 30];
console.log(mostFreqEle(arr));

Output
30

Next Article
Article Tags :
Practice Tags :

Similar Reads