GeeksforGeeks App
Open App
Browser
Continue

# 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 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

Recommended Practice

Below is the implementation:

## C++

 `// C++ program to count all words with count``// exactly 2.``#include ``using` `namespace` `std;` `// Returns count of words with frequency``// exactly 2.``int` `countWords(string str[], ``int` `n)``{``    ``unordered_map 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;``}`

## Java

 `// 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 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 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`

## Python3

 `# 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 code``s ``=` `[ ``"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#

 `// 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 m = ``new` `Dictionary();``        ` `        ``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 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`

## Javascript

 ``

Output

`1`

Time Complexity : O(N)
Auxiliary Space: O(N)

#### Method 2: Using Built-in Python functions:

• 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:

## C++

 `// C++ program for the above approach` `#include ``#include ``#include ``using` `namespace` `std;` `int` `countWords(vector s, ``int` `n)``{``    ``// Calculating frequency using unordered_map``    ``unordered_map freq;``    ``for` `(``int` `i = 0; i < n; i++) {``        ``freq[s[i]]++;``    ``}``    ``int` `count = 0;``    ``// Traversing in freq dictionary``    ``for` `(``auto``& it : freq) {``        ``if` `(it.second == 2) {``            ``count++;``        ``}``    ``}``    ``return` `count;``}` `// Driver code``int` `main()``{``    ``vector s``        ``= { ``"hate"``, ``"love"``, ``"peace"``, ``"love"``, ``"peace"``,``            ``"hate"``, ``"love"``, ``"peace"``, ``"love"``, ``"peace"` `};``    ``int` `n = s.size();``    ``cout << countWords(s, n) << endl;``    ``return` `0;``}` `// This code is contributed by prince`

## Java

 `import` `java.util.HashMap;``import` `java.util.Map;``import` `java.util.List;``import` `java.util.ArrayList;` `public` `class` `Main {``    ``public` `static` `int` `countWords(List s, ``int` `n) {``        ``// Calculating frequency using HashMap``        ``Map freq = ``new` `HashMap();``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``String key = s.get(i);``            ``if` `(freq.containsKey(key)) {``                ``freq.put(key, freq.get(key) + ``1``);``            ``} ``else` `{``                ``freq.put(key, ``1``);``            ``}``        ``}``        ``int` `count = ``0``;``        ``// Traversing in freq dictionary``        ``for` `(Map.Entry entry : freq.entrySet()) {``            ``if` `(entry.getValue() == ``2``) {``                ``count++;``            ``}``        ``}``        ``return` `count;``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args) {``        ``List s = ``new` `ArrayList();``        ``s.add(``"hate"``);``        ``s.add(``"love"``);``        ``s.add(``"peace"``);``        ``s.add(``"love"``);``        ``s.add(``"peace"``);``        ``s.add(``"hate"``);``        ``s.add(``"love"``);``        ``s.add(``"peace"``);``        ``s.add(``"love"``);``        ``s.add(``"peace"``);``        ``int` `n = s.size();``        ``System.out.println(countWords(s, n));``    ``}``}`

## Python

 `# importing Counter from collections``from` `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 code``s ``=` `[``"hate"``, ``"love"``, ``"peace"``, ``"love"``,``     ``"peace"``, ``"hate"``, ``"love"``, ``"peace"``,``     ``"love"``, ``"peace"``]``n ``=` `len``(s)``print``(countWords(s, n))` `# This code is contributed by vikkycirus`

## C#

 `using` `System;``using` `System.Collections.Generic;``using` `System.Linq;` `class` `Program {``    ``static` `int` `CountWords(List<``string``> s, ``int` `n)``    ``{``        ``// Calculating frequency using Dictionary``        ``Dictionary<``string``, ``int``> freq``            ``= ``new` `Dictionary<``string``, ``int``>();``        ``foreach``(``string` `word ``in` `s)``        ``{``            ``if` `(freq.ContainsKey(word))``                ``freq[word]++;``            ``else``                ``freq.Add(word, 1);``        ``}``        ``int` `count = 0;``        ``// Traversing in freq dictionary``        ``foreach``(KeyValuePair<``string``, ``int``> pair ``in` `freq)``        ``{``            ``if` `(pair.Value == 2)``                ``count++;``        ``}``        ``return` `count;``    ``}` `    ``static` `void` `Main(``string``[] args)``    ``{``        ``List<``string``> s = ``new` `List<``string``>{``            ``"hate"``, ``"love"``, ``"peace"``, ``"love"``, ``"peace"``,``            ``"hate"``, ``"love"``, ``"peace"``, ``"love"``, ``"peace"``        ``};``        ``int` `n = s.Count();``        ``Console.WriteLine(CountWords(s, n));``    ``}``}`

## Javascript

 `// Returns count of words with frequency exactly 2.``function` `countWords(strList) {``  ``// Calculating frequency using Counter``  ``const m = {};``  ``for` `(let i = 0; i < strList.length; i++) {``    ``const word = strList[i];``    ``m[word] = m[word] ? m[word] + 1 : 1;``  ``}` `  ``let count = 0;``  ``// Traversing in freq dictionary``  ``for` `(const i ``in` `m) {``    ``if` `(m[i] === 2) {``      ``count += 1;``    ``}``  ``}` `  ``return` `count;``}` `// Driver code``const s = [``"hate"``, ``"love"``, ``"peace"``, ``"love"``, ``"peace"``, ``"hate"``, ``"love"``, ``"peace"``, ``"love"``, ``"peace"``];``console.log(countWords(s));` `// This code is contributed by adityashatmfh`

Output

`1`

Time Complexity : O(n)
Auxiliary Space: O(n)

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.

My Personal Notes arrow_drop_up