(Translated by https://www.hiragana.jp/)
Counting frequencies of array elements - GeeksforGeeks
Open In App

Counting frequencies of array elements

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of non-negative integers which may contain duplicate elements. Return the frequency of each distinct element present in the array.
Examples: 

Input : arr[] = [10, 20, 10, 5, 20]
Output : [[10, 2], [20, 2], [ 5, 1]]
Explanation: Here, 10 occurs 2 times, 20 occurs 2 times, and 5 occurs once.

Input : arr[] = [10, 20, 20]
Output : [[10, 1], [20, 2]]
Explanation: Here, 10 occurs 1 time, 20 occurs 2 times.

[Naive Approach] Brute Force O(n^2) Time O(n) Space

A simple solution is to run two loops. For every item count number of times, it occurs. To avoid duplicate printing, keep track of processed items. 

C++
#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> countFreq(vector<int>& arr){
    int n = arr.size();
    
    // Mark all array elements as not visited
    vector<bool> visited(n , false);
    vector<vector<int>>ans;
    for (int i = 0; i < n; i++) {
        
        // Skip this element if already processed
        if (visited[i] == true)
            continue;

        // store the frequency
        int count = 1;
        for (int j = i + 1; j < n; j++) {
            if (arr[i] == arr[j]) {
                visited[j] = true;
                count++;
            }
            
        }
        ans.push_back({arr[i] , count});
    }
    return ans;
}

int main(){
    vector <int> arr = {10, 20, 10, 5, 20};
    vector<vector<int>>ans =  countFreq(arr);
    for (auto x : ans){
        cout << x[0] << ' '<< x[1] <<'\n';
    }
    return 0;
}
Java Python C# JavaScript

Output
10 2
20 2
5 1

[Efficient Solution] using hashing - O(n) Time and O(n) Space

An efficient solution is using a hash map (e.g. unordered_map in C++, HashMap in Java, dict in Python, or Dictionary in C#), we can store elements as keys and their frequencies as values.

C++
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

vector<vector<int>> countFreq(vector<int>& arr){
    unordered_map<int, int> mp;
    vector<vector<int>> ans;

    // Count frequency using unordered_map and 
    //build ans in order of first appearance
    for (int num : arr){
        if (mp.find(num) == mp.end()){
            mp[num] = 1;
            ans.push_back({num, 1});
        }
        else{
            mp[num]++;
            
            // Update frequency in ans list
            for (auto &x : ans){
                if (x[0] == num){
                    x[1]++;
                    break;
                }
            }
        }
    }
    return ans;
}

int main(){
    vector<int> arr = {10, 20, 10, 5, 20};
    vector<vector<int>> ans = countFreq(arr);
    for (auto x : ans){
        cout << x[0] << " " << x[1] << endl;
    }
    return 0;
}
Java Python C# JavaScript

Output
10 2
20 2
5 1

[Alternate Approach] using binary search (Space optimization)

we can find frequency of array elements using Binary search function . First we will sort the array for binary search . Our frequency of element will be '(last occ - first occ)+1' of a element in a array .          

C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> countFreq(vector<int> &arr){
    int n = arr.size();
    
    // Sort array for binary search
    sort(arr.begin(), arr.end()); 
    vector<vector<int>> ans;
    for (int i = 0; i < n; i++) {
        
        // Find first and last occurrence of arr[i]
        // using lower and upper bound 
        auto firstIter = lower_bound(arr.begin(), arr.end(), arr[i]);
        auto lastIter = upper_bound(arr.begin(), arr.end(), arr[i]);
        int firstIndex = firstIter - arr.begin();
        int lastIndex = lastIter - arr.begin() - 1;
        
        // Calculate frequency
        int fre = lastIndex - firstIndex + 1; 
        ans.push_back({arr[i], fre}); 
        
        // Skip counted elements
        i = lastIndex; 
    }
    return ans;
}

int main(){
    vector<int> arr = {10 ,20 ,10 ,5 , 20};
    vector<vector<int>> ans = countFreq(arr);
    for (auto x : ans){
        cout << x[0] << " " << x[1] << endl;
    }
    return 0;
}
Java Python C# JavaScript

Output
5 1
10 2
20 2

Time Complexity: O(n*log2n) , where O(log2n) time for binary search function .
Auxiliary Space: O(1)  


C++ Program to Count Frequency of Each Element in an Array
Article Tags :
Practice Tags :

Similar Reads