C++ Program to Find the Frequency of Elements in an Array (original) (raw)
Last Updated : 20 Mar, 2024
In C++, arrays are a type of data structure that can store a fixed-size sequential collection of elements of the same type. In this article, we will learn how to find the frequency of elements in an array in C++.
**Example:
**Input: Array: {1, 2, 3, 4, 2, 1, 3, 2, 4, 5}
**Output: Element: 1, Frequency: 2 Element: 2, Frequency: 3 Element: 3, Frequency: 2 Element: 4, Frequency: 2 Element: 5, Frequency: 1
Frequency of Elements in an Array in C++
To find the frequency of all the elements in an array in C++, we can use the unordered_map with the array elements as the key and its frequency as its value. We can then traverse the array and increment the frequency of each element.
Approach
- Create an unordered_map to store the frequency of each element. The keys of the map will be the elements from the array, and the corresponding values will be their frequencies.
- Iterate through each element of the array.
- For each element encountered in the array, increment its frequency count in the hash map. If the element is encountered for the first time, initialize its frequency count to 1.
- After traversing the entire array, iterate through the hash map. For each key-value pair in the hash map, print the element and its corresponding frequency.
C++ Program to Find the Frequency of Elements in an Array
C++ `
// C++ Program to illustrate how to find the frequency of // elements in an array #include #include using namespace std;
// Driver Code int main() { // Declaring an array of integers int arr[] = { 10, 20, 20, 10, 30, 40, 10, 20 }; int n = sizeof(arr) / sizeof(arr[0]);
// Declaring an unordered_map to store the frequency of
// elements
unordered_map<int, int> frequencyMap;
// Counting the frequency of elements
for (int i = 0; i < n; i++) {
frequencyMap[arr[i]]++;
}
// Printing the frequency of elements
cout << "Frequency of elements in the array is: "
<< endl;
for (auto& i : frequencyMap) {
cout << i.first << " -> " << i.second << endl;
}
return 0;
}
`
Output
Frequency of elements in the array is: 40 -> 1 30 -> 1 20 -> 3 10 -> 3
**Time Complexity: O(N), where N is the number of array elements.
**Auxiliary Space: O(N)