Counting frequencies of array elements

21 Jun, 2022
Given an array which may contain duplicates, print all elements and their frequencies.
Examples: 
Input :  arr[] = {10, 20, 20, 10, 10, 20, 5, 20}
Output : 10 3
         20 4
         5  1

Input : arr[] = {10, 20, 20}
Output : 10 1
         20 2 
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++
Java
Python3
C#
Javascript
// CPP program to count frequencies of array items#include <bits/stdc++.h>using namespace std;  void countFreq(int arr[], int n){    // Mark all array elements as not visited    vector<bool> visited(n, false);      // Traverse through array elements and    // count frequencies    for (int i = 0; i < n; i++) {          // Skip this element if already processed        if (visited[i] == true)            continue;          // Count frequency        int count = 1;        for (int j = i + 1; j < n; j++) {            if (arr[i] == arr[j]) {                visited[j] = true;                count++;            }        }        cout << arr[i] << " " << count << endl;    }}  int main(){    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };    int n = sizeof(arr) / sizeof(arr[0]);    countFreq(arr, n);    return 0;}
// Java program to count frequencies of array itemsimport java.util.Arrays;  class GFG{public static void countFreq(int arr[], int n){    boolean visited[] = new boolean[n];          Arrays.fill(visited, false);      // Traverse through array elements and    // count frequencies    for (int i = 0; i < n; i++) {          // Skip this element if already processed        if (visited[i] == true)            continue;          // Count frequency        int count = 1;        for (int j = i + 1; j < n; j++) {            if (arr[i] == arr[j]) {                visited[j] = true;                count++;            }        }        System.out.println(arr[i] + " " + count);    }}  // Driver codepublic static void main(String []args){    int arr[] = new int[]{ 10, 20, 20, 10, 10, 20, 5, 20 };    int n = arr.length;    countFreq(arr, n);}}  // This code contributed by Adarsh_Verma.
# Python 3 program to count frequencies# of array itemsdef countFreq(arr, n):          # Mark all array elements as not visited    visited = [False for i in range(n)]      # Traverse through array elements     # and count frequencies    for i in range(n):                  # Skip this element if already         # processed        if (visited[i] == True):            continue          # Count frequency        count = 1        for j in range(i + 1, n, 1):            if (arr[i] == arr[j]):                visited[j] = True                count += 1                  print(arr[i], count)  # Driver Codeif __name__ == '__main__':    arr = [10, 20, 20, 10, 10, 20, 5, 20]    n = len(arr)    countFreq(arr, n)      # This code is contributed by# Shashank_Sharma
// C# program to count frequencies of array itemsusing System;  class GFG{    public static void countFreq(int []arr, int n)    {        bool []visited = new bool[n];              // Traverse through array elements and        // count frequencies        for (int i = 0; i < n; i++)        {                  // Skip this element if already processed            if (visited[i] == true)                continue;                  // Count frequency            int count = 1;            for (int j = i + 1; j < n; j++)             {                if (arr[i] == arr[j])                 {                    visited[j] = true;                    count++;                }            }            Console.WriteLine(arr[i] + " " + count);        }    }          // Driver code    public static void Main(String []args)    {        int []arr = new int[]{ 10, 20, 20, 10, 10, 20, 5, 20 };        int n = arr.Length;        countFreq(arr, n);    }}  // This code has been contributed by 29AjayKumar
<script>  // JavaScript program to count frequencies of array items  function countFreq(arr, n){    let visited = Array.from({length: n}, (_, i) => false);              // Traverse through array elements and    // count frequencies    for (let i = 0; i < n; i++) {            // Skip this element if already processed        if (visited[i] == true)            continue;            // Count frequency        let count = 1;        for (let j = i + 1; j < n; j++) {            if (arr[i] == arr[j]) {                visited[j] = true;                count++;            }        }           document.write(arr[i] + " " + count + "<br/>");    }}  // Driver Code      let arr = [ 10, 20, 20, 10, 10, 20, 5, 20 ];    let n = arr.length;    countFreq(arr, n);      </script>
10 3
20 4
5 1
Time Complexity : O(n2) Auxiliary Space : O(n)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
An efficient solution is to use hashing.
C++
Java
Python3
C#
Javascript
// CPP program to count frequencies of array items#include <bits/stdc++.h>using namespace std;  void countFreq(int arr[], int n){    unordered_map<int, int> mp;      // Traverse through array elements and    // count frequencies    for (int i = 0; i < n; i++)        mp[arr[i]]++;      // Traverse through map and print frequencies    for (auto x : mp)        cout << x.first << " " << x.second << endl;}  int main(){    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };    int n = sizeof(arr) / sizeof(arr[0]);    countFreq(arr, n);    return 0;}
// Java program to count frequencies of array itemsimport java.util.*;  class GFG{      static void countFreq(int arr[], int n)    {        Map<Integer, Integer> mp = new HashMap<>();          // Traverse through array elements and        // count frequencies        for (int i = 0; i < n; i++)        {            if (mp.containsKey(arr[i]))             {                mp.put(arr[i], mp.get(arr[i]) + 1);            }             else            {                mp.put(arr[i], 1);            }        }        // Traverse through map and print frequencies        for (Map.Entry<Integer, Integer> entry : mp.entrySet())        {            System.out.println(entry.getKey() + " " + entry.getValue());        }    }      // Driver code    public static void main(String args[])     {        int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};        int n = arr.length;        countFreq(arr, n);    }}  // This code contributed by Rajput-Ji
# Python3 program to count frequencies # of array itemsdef countFreq(arr, n):      mp = dict()      # Traverse through array elements     # and count frequencies    for i in range(n):        if arr[i] in mp.keys():            mp[arr[i]] += 1        else:            mp[arr[i]] = 1                  # Traverse through map and print     # frequencies    for x in mp:        print(x, " ", mp[x])  # Driver codearr = [10, 20, 20, 10, 10, 20, 5, 20 ]n = len(arr)countFreq(arr, n)  # This code is contributed by # Mohit kumar 29
// C# implementation of the approachusing System;using System.Collections.Generic;   class GFG{      static void countFreq(int []arr, int n)    {        Dictionary<int, int> mp = new Dictionary<int,int>();          // Traverse through array elements and        // count frequencies        for (int i = 0; i < n; i++)        {            if (mp.ContainsKey(arr[i]))             {                var val = mp[arr[i]];                mp.Remove(arr[i]);                mp.Add(arr[i], val + 1);             }             else            {                mp.Add(arr[i], 1);            }        }                  // Traverse through map and print frequencies        foreach(KeyValuePair<int, int> entry in mp)        {            Console.WriteLine(entry.Key + " " + entry.Value);        }    }      // Driver code    public static void Main(String []args)     {        int []arr = {10, 20, 20, 10, 10, 20, 5, 20};        int n = arr.Length;        countFreq(arr, n);    }}  /* This code contributed by PrinciRaj1992 */
<script>    // JavaScript program to count // frequencies of array items  function countFreq(arr, n){    var mp = new Map();      // Traverse through array elements and    // count frequencies    for (var i = 0; i < n; i++)    {        if(mp.has(arr[i]))            mp.set(arr[i], mp.get(arr[i])+1)        else            mp.set(arr[i], 1)    }      var keys = [];    mp.forEach((value, key) => {        keys.push(key);    });    keys.sort((a,b)=> a-b);          // Traverse through map and print frequencies    keys.forEach((key) => {                  document.write(key + " " + mp.get(key)+ "<br>");    });}  var arr = [10, 20, 20, 10, 10, 20, 5, 20];var n = arr.length;countFreq(arr, n);  </script>
5 1
10 3
20 4
Time Complexity : O(n) Auxiliary Space : O(n)
In above efficient solution, how to print elements in same order as they appear in input? 
C++
Java
Python3
C#
Javascript
// CPP program to count frequencies of array items#include <bits/stdc++.h>using namespace std;  void countFreq(int arr[], int n){    unordered_map<int, int> mp;      // Traverse through array elements and    // count frequencies    for (int i = 0; i < n; i++)        mp[arr[i]]++;      // To print elements according to first    // occurrence, traverse array one more time    // print frequencies of elements and mark    // frequencies as -1 so that same element    // is not printed multiple times.    for (int i = 0; i < n; i++) {      if (mp[arr[i]] != -1)      {          cout << arr[i] << " " << mp[arr[i]] << endl;          mp[arr[i]] = -1;      }    }}  int main(){    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };    int n = sizeof(arr) / sizeof(arr[0]);    countFreq(arr, n);    return 0;}
// Java program to count frequencies of array items import java.util.*;  class GFG {      static void countFreq(int arr[], int n)     {        Map<Integer, Integer> mp = new HashMap<>();          // Traverse through array elements and         // count frequencies         for (int i = 0; i < n; i++)        {            mp.put(arr[i], mp.get(arr[i]) == null ? 1 : mp.get(arr[i]) + 1);        }          // To print elements according to first         // occurrence, traverse array one more time         // print frequencies of elements and mark         // frequencies as -1 so that same element         // is not printed multiple times.         for (int i = 0; i < n; i++)         {            if (mp.get(arr[i]) != -1)             {                System.out.println(arr[i] + " " + mp.get(arr[i]));                mp.put(arr[i], -1);            }        }    }      // Driver code    public static void main(String[] args)     {        int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};        int n = arr.length;        countFreq(arr, n);    }}  // This code contributed by Rajput-Ji
# Python3 program to count frequencies of array itemsdef countFreq(arr, n):          mp = {}          # Traverse through array elements and    # count frequencies    for i in range(n):        if arr[i] not in mp:            mp[arr[i]] = 0        mp[arr[i]] += 1              # To print elements according to first    # occurrence, traverse array one more time    # print frequencies of elements and mark    # frequencies as -1 so that same element    # is not printed multiple times.    for i in range(n):        if (mp[arr[i]] != -1):            print(arr[i],mp[arr[i]])        mp[arr[i]] = -1  # Driver code  arr = [10, 20, 20, 10, 10, 20, 5, 20]n = len(arr)countFreq(arr, n)  # This code is contributed by shubhamsingh10
// C# program to count frequencies of array items using System;using System.Collections.Generic;  class GFG {       static void countFreq(int []arr, int n)     {         Dictionary<int,int> mp = new Dictionary<int,int>();           // Traverse through array elements and         // count frequencies                   for (int i = 0 ; i < n; i++)        {            if(mp.ContainsKey(arr[i]))            {                var val = mp[arr[i]];                mp.Remove(arr[i]);                mp.Add(arr[i], val + 1);             }            else            {                mp.Add(arr[i], 1);            }        }          // To print elements according to first         // occurrence, traverse array one more time         // print frequencies of elements and mark         // frequencies as -1 so that same element         // is not printed multiple times.         for (int i = 0; i < n; i++)         {             if (mp.ContainsKey(arr[i]) && mp[arr[i]] != -1)             {                 Console.WriteLine(arr[i] + " " + mp[arr[i]]);                 mp.Remove(arr[i]);                mp.Add(arr[i], -1);             }         }     }       // Driver code     public static void Main(String[] args)     {         int []arr = {10, 20, 20, 10, 10, 20, 5, 20};         int n = arr.Length;         countFreq(arr, n);     } }   // This code is contributed by Princi Singh
<script>    // Javascript program to count frequencies of array items  function countFreq(arr, n){    var mp = new Map();      // Traverse through array elements and    // count frequencies    for (var i = 0; i < n; i++)    {        if(mp.has(arr[i]))            mp.set(arr[i], mp.get(arr[i])+1)        else            mp.set(arr[i], 1)    }          // To print elements according to first    // occurrence, traverse array one more time    // print frequencies of elements and mark    // frequencies as -1 so that same element    // is not printed multiple times.    for (var i = 0; i < n; i++) {      if (mp.get(arr[i]) != -1)      {          document.write( arr[i] + " " + mp.get(arr[i]) + "<br>");          mp.set(arr[i], -1);      }    }}  var arr = [10, 20, 20, 10, 10, 20, 5, 20];var n = arr.length;countFreq(arr, n);  // This code is contributed by rrrtnx.</script>
10 3
20 4
5 1
Time Complexity : O(n) Auxiliary Space : O(n)
This problem can be solved in Java using Hashmap. Below is the program. 
C++
Java
Python3
C#
Javascript
// C++ program to count frequencies of// integers in array using Hashmap#include <bits/stdc++.h>using namespace std;  void frequencyNumber(int arr[],int size){      // Creating a HashMap containing integer  // as a key and occurrences as a value  unordered_map<int,int>freqMap;    for (int i=0;i<size;i++) {    freqMap[arr[i]]++;  }    // Printing the freqMap  for (auto it : freqMap) {    cout<<it.first<<" "<<it.second<<endl;  }}  int main(){  int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};  int size = sizeof(arr)/sizeof(arr[0]);  frequencyNumber(arr,size);}  // This code is contributed by shinjanpatra.
// Java program to count frequencies of// integers in array using Hashmapimport java.io.*;import java.util.*;class OccurenceOfNumberInArray {    static void frequencyNumber(int arr[], int size)    {        // Creating a HashMap containing integer        // as a key and occurrences as a value        HashMap<Integer, Integer> freqMap            = new HashMap<Integer, Integer>();          for (int i=0;i<size;i++) {            if (freqMap.containsKey(arr[i])) {                  // If number is present in freqMap,                // incrementing it's count by 1                freqMap.put(arr[i], freqMap.get(arr[i]) + 1);            }            else {                  // If integer is not present in freqMap,                // putting this integer to freqMap with 1 as it's value                freqMap.put(arr[i], 1);            }        }          // Printing the freqMap        for (Map.Entry entry : freqMap.entrySet()) {            System.out.println(entry.getKey() + " " + entry.getValue());        }    }      // Driver Code    public static void main(String[] args)    {        int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};        int size = arr.length;        frequencyNumber(arr,size);    }}
# Python program to count frequencies of# integers in array using Hashmap  def frequencyNumber(arr,size):    # Creating a HashMap containing integer        # as a key and occurrences as a value        freqMap = {}           for i in range(size):            if (arr[i] in freqMap):                   # If number is present in freqMap,                # incrementing it's count by 1                freqMap[arr[i]] = freqMap[arr[i]] + 1            else:                   # If integer is not present in freqMap,                # putting this integer to freqMap with 1 as it's value                freqMap[arr[i]] = 1           # Printing the freqMap        for key, value in freqMap.items():            print(f"{key} {value}")  # Driver Codearr = [10, 20, 20, 10, 10, 20, 5, 20]size = len(arr)frequencyNumber(arr,size)  # This code is contributed by shinjanpatra
// C# program to count frequencies of// integers in array using Hashmapusing System;using System.Collections.Generic; class GFG{  static void frequencyNumber(int []arr,int size)  {      // Creating a Dictionary containing integer    // as a key and occurrences as a value    Dictionary<int, int> freqMap = new Dictionary<int,int>();      for(int i = 0; i < size; i++){      if (freqMap.ContainsKey(arr[i]))       {        var val = freqMap[arr[i]];        freqMap.Remove(arr[i]);        freqMap.Add(arr[i], val + 1);       }       else      {        freqMap.Add(arr[i], 1);      }    }      // Printing the freqMap    foreach(KeyValuePair<int, int> entry in freqMap)    {      Console.WriteLine(entry.Key + " " + entry.Value);    }  }    public static void Main(String []args)   {    int []arr = {10, 20, 20, 10, 10, 20, 5, 20};    int size = arr.Length;    frequencyNumber(arr,size);  }}// This code is contributed by Taranpreet
<script>// Javascript program to count frequencies of// integers in array using Hashmap  function frequencyNumber(arr,size){    // Creating a HashMap containing integer        // as a key and occurrences as a value        let freqMap            = new Map();           for (let i=0;i<size;i++) {            if (freqMap.has(arr[i])) {                   // If number is present in freqMap,                // incrementing it's count by 1                freqMap.set(arr[i], freqMap.get(arr[i]) + 1);            }            else {                   // If integer is not present in freqMap,                // putting this integer to freqMap with 1 as it's value                freqMap.set(arr[i], 1);            }        }           // Printing the freqMap        for (let [key, value] of freqMap.entries()) {            document.write(key + " " + value+"<br>");        }}  // Driver Codelet arr=[10, 20, 20, 10, 10, 20, 5, 20];let size = arr.length;frequencyNumber(arr,size);  // This code is contributed by patel2127</script>
5 1
10 3
20 4
Time Complexity: O(n) since using a single loop to track frequencyAuxiliary Space: O(n) for hashmap
Ajit kumar panigrahy
mohit kumar 29
Shashank_Sharma
Adarsh_Verma
29AjayKumar
Rajput-Ji
princiraj1992
princi singh
neo_700
SHUBHAMSINGH10
sanjoy_62
itsok
rrrtnx
patel2127
kk9826225
simmytarika5
surinderdawra388
shinjanpatra
singhh3010
polymatir3j
cpp-unordered_map
frequency-counting
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
What is Hashing | A Complete Tutorial
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Hashing | Set 1 (Introduction)
Internal Working of HashMap in Java
Longest Consecutive Subsequence