Challenge: Word Frequency
Completed
Read n and then n words. Print every different word with how many times it appeared, in alphabetical order, like apple 2.
Input
n, then n words (small letters).
Output
One word count line per different word, sorted.
Example
Input
5 pear apple pear fig apple
Output
apple 2 fig 1 pear 2
Editor
C++
Hints
A map<string, int> keeps words sorted and counts[w]++ counts them.
Loop over the map with for (const auto& [word, c] : counts).
Solution explanation
A map does both jobs at once: counting with [] and keeping the keys in alphabetical order.
Show solution
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
map<string, int> counts;
for (int i = 0; i < n; i++) {
string w;
cin >> w;
counts[w]++;
}
for (const auto& [word, c] : counts) {
cout << word << " " << c << "\n";
}
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module