Count words that appear exactly two times in an array of words

Given an array of n words. Some words are repeated twice, we need count such words.
Examples:

Input : s[] = {"hate", "love", "peace", "love", 
               "peace", "hate", "love", "peace", 
               "love", "peace"};
Output : 1
There is only one word "hate" that appears twice

Input : s[] = {"Om", "Om", "Shankar", "Tripathi", 
                "Tom", "Jerry", "Jerry"};
Output : 2
There are two words "Om" and "Jerry" that appear
twice.

Source : Amazon Interview

  1. Traverse the given array, store counts of words in a hash table
  2. Traverse hash table and count all words with count 2.

Below is C++ implementation.

// C++ program to count all words with count
// exavtly 2.
#include <bits/stdc++.h>
using namespace std;

// Returns count of words with frequency
// exactly 2.
int countWords(string str[], int n)
{
    unordered_map<string, int> m;
    for (int i = 0; i < n; i++)
        m[str[i]] += 1;

    int res = 0;
    for (auto it = m.begin(); it != m.end(); it++)
        if ((it->second == 2))
            res++;

    return res;
}

// Driver code
int main()
{
    string s[] = { "hate", "love", "peace", "love",
                   "peace", "hate", "love", "peace",
                   "love", "peace" };
    int n = sizeof(s) / sizeof(s[0]);
    cout << countWords(s, n);
    return 0;
}

Output:

1

This article is contributed by Saumya Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.