Program to find frequency of each element in a vector using map in C++
Given a vector vec, the task is to find the frequency of each element of vec using a map.
Examples:
Input: vec = {1, 2, 2, 3, 1, 4, 4, 5}
Output:
1 2
2 2
3 1
4 2
5 1
Explanation:
1 has occurred 2 times
2 has occurred 2 times
3 has occurred 1 times
4 has occurred 2 times
5 has occurred 1 times
Input: v1 = {6, 7, 8, 6, 4, 1}
Output:
1 1
4 1
6 2
7 1
8 1
Explanation:
1 has occurred 1 times
4 has occurred 1 times
6 has occurred 2 times
7 has occurred 1 times
8 has occurred 1 times
Approach:
We can find the frequency of elements in a vector using given four steps efficiently:
- Traverse the elements of the given vector vec.
- check whether the current element is present in the map or not.
- If it is present, then update the frequency of the current element, else insert the element with frequency 1 as shown below:
- Traverse the map and print the frequency of each element stored as a mapped value.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void printFrequency(vector< int > vec)
{
map< int , int > M;
for ( int i = 0; vec[i]; i++) {
if (M.find(vec[i]) == M.end()) {
M[vec[i]] = 1;
}
else {
M[vec[i]]++;
}
}
for ( auto & it : M) {
cout << it.first << ' '
<< it.second << '\n' ;
}
}
int main()
{
vector< int > vec = { 1, 2, 2, 3, 1, 4, 4, 5 };
printFrequency(vec);
return 0;
}
|
Output:
1 2
2 2
3 1
4 2
5 1
Complexity Analysis:
Time Complexity: O(n log n)
For a given vector of size n, we are iterating over it once and the time complexity for searching elements in the map is O(log n). So the time complexity is O(n log n)
Space Complexity: O(n)
For a given vector of size n, we are using an extra map which can have maximum of n key-values, so space complexity is O(n)
Last Updated :
29 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...