Frequency Measuring Techniques for Competitive Programming

Measuring the frequency of elements in an array is a really handy skill and is required a lot of competitive coding problems. We, in lot of problems are required to measure frequency of various elements like numbers, alphabets, symbols, etc. as a part of our problem.

Naive method

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 2
         20 1

We run two loops. For every item count number of times it occurs. To avoid duplicate printing, keep track of processed items.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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<int> 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count frequencies 
// of array items
import java.util.*;
  
class GFG
{
static void countFreq(int arr[], int n)
{
    // Mark all array elements as not visited
    boolean []visited = new boolean[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++;
            }
        }
        System.out.println(arr[i] + " " + count);
    }
}
  
// 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 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to count frequencies 
# of array items
def 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):
            if arr[i] == arr[j]:
                visited[j] = True
                count += 1 
        print(arr[i], count)
      
# Driver code
a = [10, 20, 20, 10, 10, 20, 5, 20]
  
n = len(a)
  
countFreq(a, n)
  
# This code is contributed 
# by Mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count frequencies 
// of array items
using System;
      
class GFG
{
static void countFreq(int []arr, int n)
{
    // Mark all array elements as not visited
    Boolean []visited = new Boolean[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 = { 10, 20, 20, 10,
                  10, 20, 5, 20 };
    int n = arr.Length;
    countFreq(arr, n);
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


Output:

10 3
20 4
5 1

Optimized methods :

Measuring frequencies when elements are limited by value
If our input array has small values, we can use array elements as index in a count array and increment count. In below example, elements are maximum 10.

Input :  arr[] = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10}
         limit = 10
Output : 1 1
         2 1
         3 1
         5 3
         6 3
         10 2

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to count frequencies of array items
// having small values.
#include <bits/stdc++.h>
using namespace std;
   
void countFreq(int arr[], int n, int limit)
{
    // Create an array to store counts. The size
    // of array is limit+1 and all values are 
    // initially 0
    vector<int> count(limit+1, 0);
   
    // Traverse through array elements and
    // count frequencies (assuming that elements
    // are limited by limit)
    for (int i = 0; i < n; i++) 
        count[arr[i]]++;
   
    for (int i = 0; i <= limit; i++) 
       if (count[i] > 0)
        cout << i << " " << count[i] << endl;
      
}
   
int main()
{
    int arr[] = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10};
    int n = sizeof(arr) / sizeof(arr[0]);
    int limit = 10;
    countFreq(arr, n, limit);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count frequencies of array items
// having small values.
class GFG
{
      
static void countFreq(int arr[], int n, int limit)
{
    // Create an array to store counts. The size
    // of array is limit+1 and all values are 
    // initially 0
    int []count = new int[limit + 1];
  
    // Traverse through array elements and
    // count frequencies (assuming that elements
    // are limited by limit)
    for (int i = 0; i < n; i++) 
        count[arr[i]]++;
  
    for (int i = 0; i <= limit; i++) 
    if (count[i] > 0)
            System.out.println(i + " " + count[i]);
}
  
// Driver Code
public static void main(String[] args) 
{
    int arr[] = {5, 5, 6, 6, 5, 6, 1, 2, 3, 10, 10};
    int n = arr.length;
    int limit = 10;
    countFreq(arr, n, limit);
}
}
  
// This code is contributed by PrinciRaj1992 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count frequencies of 
// array items having small values.
using System;
      
class GFG
{
      
static void countFreq(int []arr, 
                      int n, int limit)
{
    // Create an array to store counts. 
    // The size of array is limit+1 and 
    // all values are initially 0
    int []count = new int[limit + 1];
  
    // Traverse through array elements and
    // count frequencies (assuming that
    // elements are limited by limit)
    for (int i = 0; i < n; i++) 
        count[arr[i]]++;
  
    for (int i = 0; i <= limit; i++) 
    if (count[i] > 0)
            Console.WriteLine(i + " "
                              count[i]);
}
  
// Driver Code
public static void Main(String[] args) 
{
    int []arr = {5, 5, 6, 6, 5, 6, 
                 1, 2, 3, 10, 10};
    int n = arr.Length;
    int limit = 10;
    countFreq(arr, n, limit);
}
}
  
// This code is contributed 
// by Princi Singh

chevron_right


Output:

1 1
2 1
3 1
5 3
6 3
10 2

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to count frequencies of array items
#include <bits/stdc++.h>
using namespace std;
  
const int limit = 255; 
  
void countFreq(string str)
{
    // Create an array to store counts. The size
    // of array is limit+1 and all values are 
    // initially 0
    vector<int> count(limit+1, 0);
   
    // Traverse through string characters and
    // count frequencies 
    for (int i = 0; i < str.length(); i++) 
        count[str[i]]++;
   
    for (int i = 0; i <= limit; i++) 
       if (count[i] > 0)
        cout << (char)i << " " << count[i] << endl;
      
}
   
int main()
{
    string str = "GeeksforGeeks";
    countFreq(str);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count frequencies of array items
class GFG 
{
static int limit = 255
  
static void countFreq(String str)
{
    // Create an array to store counts. The size
    // of array is limit+1 and all values are 
    // initially 0
    int []count= new int[limit + 1];
  
    // Traverse through string characters and
    // count frequencies 
    for (int i = 0; i < str.length(); i++) 
        count[str.charAt(i)]++;
  
    for (int i = 0; i <= limit; i++) 
    if (count[i] > 0)
        System.out.println((char)i + " " + count[i]);
}
  
// Driver Code
public static void main(String[] args)
{
    String str = "GeeksforGeeks";
    countFreq(str);
}
}
  
// This code is contributed by PrinciRaj1992

chevron_right


C#

// C# program to count frequencies
// of array items
using System;

class GFG
{
static int limit = 255;

static void countFreq(String str)
{
// Create an array to store counts.
// The size of array is limit+1 and
// all values are initially 0
int []count = new int[limit + 1];

// Traverse through string characters and
// count frequencies
for (int i = 0; i < str.Length; i++) count[str[i]]++; for (int i = 0; i <= limit; i++) if (count[i] > 0)
Console.WriteLine((char)i + ” ” +
count[i]);
}

// Driver Code
public static void Main(String[] args)
{
String str = “GeeksforGeeks”;
countFreq(str);
}
}

// This code is contributed by 29AjayKumar

Output:

G 2
e 4
f 1
k 2
o 1
r 1
s 2

Measuring frequencies when elements are in limited range
For example consider a string containing only upper case alphabets. Elements of string are limited in range from ‘A’ to ‘Z’. The idea is to subtract smallest element (‘A’ in this example) to get index of the element.

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to count frequencies of array items
#include <bits/stdc++.h>
using namespace std;
  
const int limit = 25; 
  
void countFreq(string str)
{
    // Create an array to store counts. The size
    // of array is limit+1 and all values are 
    // initially 0
    vector<int> count(limit+1, 0);
   
    // Traverse through string characters and
    // count frequencies 
    for (int i = 0; i < str.length(); i++) 
        count[str[i] - 'A']++;
   
    for (int i = 0; i <= limit; i++) 
       if (count[i] > 0)
        cout << (char)(i + 'A') << " " << count[i] << endl;
      
}
   
int main()
{
    string str = "GEEKSFORGEEKS";
    countFreq(str);
    return 0;
}

chevron_right


Output:

E 4
F 1
G 2
K 2
O 1
R 1
S 2

Measuring frequencies if no range and no limit
The idea is to use hashing (unordered_map in C++ and HashMap in Java) to get frequencies.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

5 1
10 3
20 4
Output:

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?

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

10 3
20 4
5 1
Output:

10 3
20 4
5 1

Time Complexity : O(n)
Auxiliary Space : O(n)

In Java, we can get elements in same order using LinkedHashMap. Therefore we do not need an extra loop.

Lot of problems are based on frequency measurement and will be a cheesecake if we know how to calculate frequency of various elements in a given array. For example try the given below problems which are based on frequency measurement:

  1. Anagrams
  2. Sorting Elements of an Array by Frequency
  3. Single Number

This article is contributed by Aditya Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up