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

07 Aug, 2021
Given an array of n words. Some words are repeated twice, we need to 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
Below is the implementation: 
C++
Java
Python3
C#
Javascript
// C++ program to count all words with count// exactly 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 codeint 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;}
// Java program to count all words with count// exactly 2.import java.util.HashMap;import java.util.Map;public class GFG {          // Returns count of words with frequency    // exactly 2.    static int countWords(String str[], int n)    {        // map to store count of each word        HashMap<String, Integer> m = new HashMap<>();                 for (int i = 0; i < n; i++){            if(m.containsKey(str[i])){                int get = m.get(str[i]);                m.put(str[i], get + 1);            }            else{                m.put(str[i], 1);            }        }                     int res = 0;        for (Map.Entry<String, Integer> it: m.entrySet()){            if(it.getValue() == 2)                res++;        }                         return res;    }          // Driver code    public static void main(String args[])    {        String s[] = { "hate", "love", "peace", "love",                       "peace", "hate", "love", "peace",                       "love", "peace" };        int n = s.length;        System.out.println( countWords(s, n));    }}// This code is contributed by Sumit Ghosh
# Python program to count all# words with count# exactly 2.  # Returns count of words with frequency# exactly 2.def countWords(stri, n):    m = dict()    for i in range(n):        m[stri[i]] = m.get(stri[i],0) + 1      res = 0    for i in m.values():        if i == 2:            res += 1      return res  # Driver codes = [ "hate", "love", "peace", "love",      "peace", "hate", "love", "peace",                "love", "peace" ]n = len(s)print(countWords(s, n)) # This code is contributed# by Shubham Rana
// C# program to count all words with count// exactly 2.using System;using System.Collections.Generic; class GFG{         // Returns count of words with frequency    // exactly 2.    static int countWords(String []str, int n)    {        // map to store count of each word        Dictionary<String,int> m = new Dictionary<String,int>();                 for (int i = 0; i < n; i++)        {            if(m.ContainsKey(str[i]))            {                int get = m[str[i]];                m.Remove(str[i]);                m.Add(str[i], get + 1);            }            else            {                m.Add(str[i], 1);            }        }                     int res = 0;        foreach(KeyValuePair<String, int> it in m)        {            if(it.Value == 2)                res++;        }                         return res;    }         // Driver code    public static void Main(String []args)    {        String []a = { "hate", "love", "peace", "love",                    "peace", "hate", "love", "peace",                    "love", "peace" };        int n = a.Length;        Console.WriteLine( countWords(a, n));    }} // This code is contributed by Rajput-Ji
<script> // Javascript program to count all words with count// exactly 2. // Returns count of words with frequency// exactly 2.function countWords(str, n){    var m = new Map();    for (var i = 0; i < n; i++)    {        if(m.has(str[i]))            m.set(str[i], m.get(str[i])+1)        else            m.set(str[i], 1)    }     var res = 0;     m.forEach((value, key) => {                 if ((value == 2))            res++;    });    return res;} // Driver codevar s = ["hate", "love", "peace", "love",               "peace", "hate", "love", "peace",               "love", "peace" ];var n = s.length;document.write( countWords(s, n)); </script>
1
Count the frequencies of every word using the Counter function
Traverse in frequency dictionary
Check which word has frequency 2. If so, increase the count
Print Count
Below is the implementation:
Python
# importing Counter from collectionsfrom collections import Counter # Python program to count all words with count exactly 2.# Returns count of words with frequency exactly 2.def countWords(stri, n):       # Calculating frequency using Counter    m = Counter(stri)     count = 0    # Traversing in freq dictionary    for i in m:        if m[i] == 2:            count += 1     return count # Driver codes = ["hate", "love", "peace", "love",     "peace", "hate", "love", "peace",     "love", "peace"]n = len(s)print(countWords(s, n)) # This code is contributed by vikkycirus
1
YouTubeGeeksforGeeks502K subscribersCount words that appear exactly two times in an array of words | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:46•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Ast7ctj1pqA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Saumya Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
Rajput-Ji
vikkycirus
noob2000
bunnyram19
simranarora5sos
Amazon
cpp-unordered_map
STL
Strings
Amazon
Strings
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Reverse words in a given string
Top 50 String Coding Problems for Interviews