 GeeksforGeeks App
Open App Browser
Continue

# 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:

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 ``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)

My Personal Notes arrow_drop_up