CP: The most common word

A text has many words. Find the word that appears most often.

What to build

Read words with cin >> word until the input ends and count them in a map<string, int>. Print the most common word and its count. If two words tie, print the one that comes first alphabetically.

Requirements

  • Read words until the input ends
  • Count with map<string, int>
  • On a tie, print the alphabetically smaller word

Input

Lowercase words separated by spaces and newlines. There is at least one word, and at most 50,000 words.

Output

WORD COUNT for the most common word.

Constraints

At most 50,000 words, each up to 20 letters.

Example

Input:

the cat and the dog and the bird

Output:

the 3

Why it works

A map visits its keys in alphabetical order. Scanning it and replacing the best only when a count is strictly larger keeps the first (alphabetically smallest) word on a tie. Counting is O(n log n).

Examples

Example 1 · Input
the cat and the dog and the bird
Expected output
the 3
Example 2 · Input
red blue
Expected output
blue 1

Hints

Hint 1

map<string, int> freq; then freq[word]++ for each word.

Hint 2

Loop over the map with for (auto& kv : freq) and keep the biggest count.

Hint 3

Use > and not >= so ties keep the earlier word.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main() {
    map<string, int> freq;
    string w;
    while (cin >> w) freq[w]++;
    string best;
    int bestCount = 0;
    for (auto& kv : freq) {
        if (kv.second > bestCount) {
            bestCount = kv.second;
            best = kv.first;
        }
    }
    cout << best << " " << bestCount << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: The STL toolbox for contests →