×

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

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.

C++ Program to move all zeros to the end of the array

Write a program to move all the zeros in the arr[] to the end. The order of the non-zero elements should not be altered and all the zeros should be...

3 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 minutes read.

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was...

4 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

6 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 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.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.