Count of words that are present in all the given sentences

Given n sentences. The task is to count the number of words that appear in all of these sentences. Note that every word consists of only lowercase English alphabets.

Examples:

Input: arr[] = {
“there is a cow”,
“cow is our mother”,
“cow gives us milk and milk is sweet”,
“there is a boy who loves cow”}
Output: 2
Only the words “is” and “cow” appear in all of the sentences.

Input: arr[] = {
“abc aac abcd ccc”,
“ac aa abc cca”,
“abca aaac abcd ccc”}
Output: 0



Naive Approach: The naive approach is to take every word of the first sentence and compare it with rest of the lines if it is also present in all lines then increment the count.

Efficient Approach: For all the words of the first sentence, we can check if it is also present in all the other sentences in constant time by using a map. Store all the words of the first sentence in a map and check how many of these stored words are present in all of the other sentences.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the count of common words
// in all the sentences
int commonWords(vector<string> S)
{
    int m, n, i, j;
  
    // To store separate words
    string str;
  
    // It will be used to check if a word is present
    // in a particuler string
    unordered_map<string, bool> has;
  
    // To store all the words of first string
    vector<pair<string, bool> > ans;
  
    pair<string, bool> tmp;
  
    // m will store number of strings in given vector
    m = S.size();
  
    i = 0;
  
    // Extract all words of first string and store it in ans
    while (i < S[0].size()) {
        str = "";
        while (i < S[0].size() && S[0][i] != ' ') {
            str += S[0][i];
            i++;
        }
  
        // Increase i to get at starting index
        // of the next word
        i++;
  
        // If str is not empty store it in map
        if (str != "") {
            tmp = make_pair(str, true);
            ans.push_back(tmp);
        }
    }
  
    // Start from 2nd line check if any word of
    // the first string did not match with
    // some word in the current line
    for (j = 1; j < m; j++) {
        has.clear();
        i = 0;
  
        while (i < S[j].size()) {
            str = "";
            while (i < S[j].size() && S[j][i] != ' ') {
                str += S[j][i];
                i++;
            }
            i++;
            if (str != "") {
                has[str] = true;
            }
        }
  
        // Check all words of this vector
        // if it is not present in current line
        // make it false
        for (int k = 0; k < ans.size(); k++) {
            if (ans[k].second != false
                && has[ans[k].first] == false) {
                ans[k].second = false;
            }
  
            // This line is used to consider only distinct words
            else if (ans[k].second != false
                     && has[ans[k].first] == true) {
                has[ans[k].first] = false;
            }
        }
    }
  
    // This function will print
    // the count of common words
    int cnt = 0;
  
    // If current word appears in all the sentences
    for (int k = 0; k < ans.size(); k++) {
        if (ans[k].second == true)
            cnt++;
    }
  
    return cnt;
}
  
// Driver code
int main()
{
    vector<string> S;
    S.push_back("there is a cow");
    S.push_back("cow is our mother");
    S.push_back("cow gives us milk and milk is sweet");
    S.push_back("there is a boy who loves cow");
  
    cout << commonWords(S);
  
    return 0;
}

chevron_right


Python3

# Python3 implementation of the approach
from collections import defaultdict

# Function to return the count of
# common words in all the sentences
def commonWords(S):

# It will be used to check if a word
# is present in a particuler string
has = defaultdict(lambda:False)

# To store all the words of first string
ans = []

# m will store number of strings
# in given vector
m = len(S)

i = 0

# Extract all words of first string
# and store it in ans
while i < len(S[0]): string = "" while i < len(S[0]) and S[0][i] != ' ': string += S[0][i] i += 1 # Increase i to get at starting # index of the next word i += 1 # If str is not empty store it in map if string != "": ans.append([string, True]) # Start from 2nd line check if any word # of the first string did not match with # some word in the current line for j in range(1, m): has.clear() i = 0 while i < len(S[j]): string = "" while i < len(S[j]) and S[j][i] != ' ': string += S[j][i] i += 1 i += 1 if string != "": has[string] = True # Check all words of this vector # if it is not present in current # line make it false for k in range(0, len(ans)): if (ans[k][1] != False and has[ans[k][0]] == False): ans[k][1] = False # This line is used to consider # only distinct words elif (ans[k][1] != False and has[ans[k][0]] == True): has[ans[k][0]] = False # This function will print # the count of common words cnt = 0 # If current word appears in all # the sentences for k in range(0, len(ans)): if ans[k][1] == True: cnt += 1 return cnt # Driver code if __name__ == "__main__": S = [] S.append("there is a cow") S.append("cow is our mother") S.append("cow gives us milk and milk is sweet") S.append("there is a boy who loves cow") print(commonWords(S)) # This code is contributed by Rituraj Jain [tabbyending]

Output:

2


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : rituraj_jain