Count Frequency Using Map

Count Frequency Using Map

Medium C++ STL 34 views
Explanation Complexity

Problem Statement

Count how many times each element appears.
Real Life: Vote counting, inventory management.

Input Format

An integer n (number of elements)
Then n integers.

Output Format

Each unique element with its count.

Example

7
1 2 2 3 1 2 4
1 -> 2
2 -> 3
3 -> 1
4 -> 1

Constraints

• n ≥ 1

• Elements can repeat

• Order does not matter

Concept Explanation

We need to count how many times each value appears.
This is useful in real life for vote counting or inventory management.

Step-by-Step Explanation

1.Take input size n.

2.Read n elements one by one.

3.Use a map to store:

• key → element

• value → count

4.For each element:

• If it already exists in map, increase count.

• If not, insert it with count 1.

5.Traverse the map.

6.Print each element with its frequency.

Concept Explanation

We need to count how many times each value appears.
This is useful in real life for vote counting or inventory management.

Step-by-Step Explanation

1.Take input size n.

2.Read n elements one by one.

3.Use a map to store:

• key → element

• value → count

4.For each element:

• If it already exists in map, increase count.

• If not, insert it with count 1.

5.Traverse the map.

6.Print each element with its frequency.

Input / Output Format

Input Format
An integer n (number of elements)
Then n integers.
Output Format
Each unique element with its count.
Constraints
• n ≥ 1

• Elements can repeat

• Order does not matter

Examples

Input:
7 1 2 2 3 1 2 4
Output:
1 -> 2 2 -> 3 3 -> 1 4 -> 1

Example Solution (Public)

C++
void stl_q9_frequency_map() {
    vector<int> numbers = {1, 2, 2, 3, 1, 4, 2, 3, 1};
    map<int, int> frequency;
    
    // Count frequencies
    for(int num : numbers) {
        frequency[num]++;
    }
    
    // Print frequencies
    cout << "Element frequencies:" << endl;
    for(auto pair : frequency) {
        cout << pair.first << " appears " << pair.second << " times" << endl;
    }
}

Official Solution Code

void stl_q9_frequency_map() {
    vector<int> numbers = {1, 2, 2, 3, 1, 4, 2, 3, 1};
    map<int, int> frequency;
    
    // Count frequencies
    for(int num : numbers) {
        frequency[num]++;
    }
    
    // Print frequencies
    cout << "Element frequencies:" << endl;
    for(auto pair : frequency) {
        cout << pair.first << " appears " << pair.second << " times" << endl;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.