×

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array.

Methods:

Methods that can be used to find out the frequencies of elements in an array in the C++ programming language.

Method 1: Naive technique (approach) with the extra-space method

Method 2: Naive technique (approach) without the extra-space method

Method 3: Using the sorting method

Method 4: Using the hash map method

1. Naive technique with the extra-space method

In this technique, using two "for" loops, we can count the frequency of every element.

  1. Create an array of size "n" in order to see the status of the visited elements.
  2. From index zero to n, execute a loop. If "visited[i] == 1," then that element is skipped.
  3. Otherwise, make a "var count = 1" to retain the frequency count.
  4. Execute a loop from the index "i+1" to "n."
  5. If "arry[i] == arry[j]," then the count is increased by one and "visited[j]" is set to one.
  6. After the "for" loop has finished iterating, print the element along with the count value.

Example

#include <bits/stdc++.h>
using namespace std;
/*  To run the program, use the main() function. */
int main() 
{ 
int arry[] = {100, 300, 100, 200, 100, 200, 300, 100}; 
    	int n = sizeof(arry)/sizeof(arry[0]); 
int visit[n];
for(int i=0; i<n; i++)
{
	if(visit[i]!=1)
	{
          	 		int count = 1;
           			for(int j=i+1; j<n; j++)
		{
		if(arry[i]==arry[j])
		{
                 				count++;
                 				visit[j]=1;
         				}
        			}
	 	cout<<arry[i]<<" is repeated "<<count<<" times "<<endl;
         		}
     	}
	return 0; 
}

Output:

Counting Frequencies of Array Elements in C++

Space Complexity and Time Complexity:

  • Space Complexity: O(n)
  • Time Complexity: O(n2)

2. Naive technique without the extra-space method

We will use the naive technique in this method to get the frequency of the elements in the supplied integer array without requiring any extra space.

Example

#include <bits/stdc++.h>
using namespace std;
void count_Frequency(int *arry, int size)
{
	for (int i = 0; i < size; i++)
	{
        		int flag = 0;
        		int count = 0;
		/* Any element's counting must be pushed to its most recent occurrence */
        		for (int j = i+1; j < size; j++)
		{
            		if (arry[i] == arry[j])	
			{
                			flag = 1;
                			break;
            		}
        		}
		/* The term "continue" is used to break the current iteration and proceeds to the following iteration in a "for" loop or a "while" loop */
        		if (flag == 1)
            		continue;
            
        		for(int j = 0;j<=i;j++)
		{
            		if(arry[i] == arry[j])
                		count +=1;
        		}
        
        		cout << arry[i] << ": " << count << endl;
    	}
}


int main()
{
   	int arry[] = {50, 80, 50, 70, 80, 100};
    	int size = sizeof(arry)/sizeof(arry[0]);
    	count_Frequency(arry, size);
	return 0;
}

Output:

Counting Frequencies of Array Elements in C++

Space Complexity and Time Complexity:

  • Space Complexity: O(1)
  • Time Complexity: O(n2)

3. Using the Sorting method

In this technique, we will sort the array and then count the frequency of the items.

Example

#include<bits/stdc++.h>
using namespace std;
void count_Distinct(int arry[], int n)
{
	sort(arry, arry + n);
 	// Traverse the sorted array
    	for (int i = 0; i < n; i++)
	{
        		int count = 1;
		/* When you come across duplicates, advance the index */
        		while (i < n - 1 && arry[i] == arry[i + 1])
		{
            		i++;
            		count++;
        		}
      	cout << arry[i] << ": " << count << endl;
    	}
}
 
/* Driver program for testing the above-mentioned function */
int main()
{
    	int arry[] = {50, 80, 50, 70, 80, 100};
    	int n = sizeof(arry) / sizeof(arry[0]);
    	count_Distinct(arry, n);
    	return 0;
}

Output:

Counting Frequencies of Array Elements in C++

Space Complexity and Time Complexity:

  • Space Complexity: O(1)
  • Time Complexity: O(nlogn)

4. Using the hash map method

In this technique, the frequency of the items will be stored using a hash-map approach.

  1. Create an "unordered_map" with the name "ump."
  2. Use a loop ("for" or "while") to iterate over the array.
  3. Set “ump[arry[i]]++”
  4. After finishing the iteration, execute a loop across map.
  5. Also, print the key-value pair.

Example

#include <bits/stdc++.h>
using namespace std;
 void count_Freq(int arry[], int n)
{
   	unordered_map<int, int> ump;
 	/* Count frequencies as you traverse the array elements */
    	for (int i = 0; i < n; i++)
	{
        		ump[arry[i]]++;
	}
 
    	// Traverse through map and print frequencies
    	for (auto x : ump)
	{	
        		cout << x.first << " occurs " << x.second << endl;
	}
}
 int main()
{
   	int arry[] = { 101, 201, 201, 101, 101, 201, 51, 201 };
    	int n = sizeof(arry) / sizeof(arry[0]);
    	count_Freq(arry, n);
    	return 0;
}

Output:

Counting Frequencies of Array Elements in C++

Related Topics

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.

C++ Mutable keyword

C++ mutable keyword Mutable class storage specifier in C++ Storage class specifiers in C are auto, register, static, and external. Typedef is also considered as a specifier of the storage...

4 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

Structure of C++ Program

Many people believe that C++, an object-oriented programming (OOP) language, is the finest language for developing demanding applications. A superset of the C language is C++. Java, a closely comparable...

4 minutes read.

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.