Skip to content
Related Articles

Related Articles

Program to find frequency of each element in a vector using map in C++
  • Last Updated : 13 Apr, 2021

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 occured 2 times 
2 has occured 2 times 
3 has occured 1 times 
4 has occured 2 times 
5 has occured 1 times 
Input: v1 = {6, 7, 8, 6, 4, 1} 
Output: 
1 1 
4 1 
6 2 
7 1 
8 1 
Explanation: 
1 has occured 1 times 
4 has occured 1 times 
6 has occured 2 times 
7 has occured 1 times 
8 has occured 1 times 
 

 

Approach: 
We can find the frequency of elements in a vector using given four steps efficiently: 
 

  1. Traverse the elements of the given vector vec.
  2. check whether the current element is present in the map or not.
  3. If it is present, then update the frequency of the current element, else insert the element with frequency 1 as shown below:
  4. 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)
{
    // Define an map
    map<int, int> M;
 
    // Traverse vector vec check if
    // current element is present
    // or not
    for (int i = 0; vec[i]; i++) {
 
        // If the current element
        // is not found then insert
        // current element with
        // frequency 1
        if (M.find(vec[i]) == M.end()) {
            M[vec[i]] = 1;
        }
 
        // Else update the frequency
        else {
            M[vec[i]]++;
        }
    }
 
    // Traverse the map to print the
    // frequency
    for (auto& it : M) {
        cout << it.first << ' '
             << it.second << '\n';
    }
}
 
// Driver Code
int main()
{
    vector<int> vec = { 1, 2, 2, 3, 1, 4, 4, 5 };
 
    // Function call
    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)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :