×

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

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

C++ STL (Standard Template Library)

Introduction C++ is a flexible type and general proposed programming language. So we need a standard library that supports C++. C++ STL (Standard Template Library) is a collection of templates that...

6 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

3 minutes read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

Single Handling in C++

Introduction: Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows...

5 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

C++ Static

What is the Static keyword? In C++, the keyword static is used to give an element some particular properties. Static elements are only given storage in the static storage region once...

4 minutes read.

Constructor Overloading

The program contains more than one constructor in a class with the same name, and different types of arguments are called constructor overloading. Calling of constructor depends on the number and types...

2 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

C++ | C Plus Plus While loop

In this article, we will discuss the C++ while loop with its syntax, use, key features, key points, pseudo code, and examples. What is the While Loop? The “while loop” is a...

4 minutes read.

sort() function in C++

This tutorial covers the various built-in sort functions found in the C++ algorithm’s library.  What Does C++ Sort Mean? The concept of sorting in C++ entails rearranging an array's elements in a...

3 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.