Count of words that are present in all the given sentences
Last Updated :
17 Apr, 2023
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 the rest of the lines if it is also present in all lines then increment the count.
- Iterate over every word of the first sentence.
- Check if the current word exists in all the rest sentences.
- If exist, increment the count by 1.
- Finally, return the value of the count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isContain(string& s1, string& s2)
{
stringstream ss(s2);
string word;
while (ss >> word) {
if (word == s1)
return true ;
}
return false ;
}
int commonWords(vector<string>& S)
{
int count = 0;
stringstream ss(S[0]);
string word;
while (ss >> word) {
bool flag = true ;
for ( int j = 1; j < S.size(); j++) {
if (isContain(word, S[j]) == false ) {
flag = false ;
break ;
}
}
if (flag)
count++;
}
return count;
}
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;
}
|
Java
import java.util.*;
import java.io.*;
public class GFG {
public static boolean isContain(String s1, String s2)
{
StringTokenizer st = new StringTokenizer(s2);
String word;
while (st.hasMoreTokens()) {
word = st.nextToken();
if (word.equals(s1))
return true ;
}
return false ;
}
public static int commonWords(Vector<String> S)
{
int count = 0 ;
StringTokenizer st = new StringTokenizer(S.get( 0 ));
String word;
while (st.hasMoreTokens()) {
boolean flag = true ;
word = st.nextToken();
for ( int j = 1 ; j < S.size(); j++) {
if (isContain(word, S.get(j)) == false ) {
flag = false ;
break ;
}
}
if (flag)
count++;
}
return count;
}
public static void main(String[] args)
{
Vector<String> S = new Vector<String>();
S.add( "there is a cow" );
S.add( "cow is our mother" );
S.add( "cow gives us milk and milk is sweet" );
S.add( "there is a boy who loves cow" );
System.out.println(commonWords(S));
}
}
|
Python3
def isContain(s1, s2):
s2 = s2.split()
return s1 in s2
def commonWords(S):
count = 0
words = S[ 0 ].split()
for word in words:
flag = True
for i in range ( 1 , len (S)):
if not isContain(word, S[i]):
flag = False
break
if flag:
count + = 1
return count
S = [ "there is a cow" , "cow is our mother" ,
"cow gives us milk and milk is sweet" , "there is a boy who loves cow" ]
print (commonWords(S))
|
Javascript
function isContain(s1, s2) {
let words = s2.split( " " );
return words.includes(s1);
}
function commonWords(S) {
let count = 0;
let words = S[0].split( " " );
for (let i = 0; i < words.length; i++) {
let flag = true ;
for (let j = 1; j < S.length; j++) {
if (!isContain(words[i], S[j])) {
flag = false ;
break ;
}
}
if (flag) {
count += 1;
}
}
return count;
}
let S = [ "there is a cow" , "cow is our mother" , "cow gives us milk and milk is sweet" , "there is a boy who loves cow" ];
console.log(commonWords(S));
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Gfg
{
static bool IsContain( string s1, string s2)
{
var words = s2.Split( ' ' );
return words.Contains(s1);
}
static int CommonWords(List< string > S)
{
int count = 0;
var words = S[0].Split( ' ' );
foreach ( var word in words)
{
bool flag = true ;
for ( int j = 1; j < S.Count; j++) {
if (!IsContain(word, S[j])) {
flag = false ;
break ;
}
}
if (flag)
count++;
}
return count;
}
static void Main( string [] args)
{
var S = new List< string >() {
"there is a cow" , "cow is our mother" ,
"cow gives us milk and milk is sweet" ,
"there is a boy who loves cow"
};
Console.WriteLine(CommonWords(S));
}
}
|
Time Complexity: O(N2), where N is the total words present in all sentences.
Auxiliary Space: O(1)
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 the other sentences.
C++
#include <bits/stdc++.h>
using namespace std;
int commonWords(vector<string> S)
{
int m, n, i, j;
string str;
unordered_map<string, bool > has;
vector<pair<string, bool > > ans;
pair<string, bool > tmp;
m = S.size();
i = 0;
while (i < S[0].size()) {
str = "" ;
while (i < S[0].size() && S[0][i] != ' ' ) {
str += S[0][i];
i++;
}
i++;
if (str != "" ) {
tmp = make_pair(str, true );
ans.push_back(tmp);
}
}
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 ;
}
}
for ( int k = 0; k < ans.size(); k++) {
if (ans[k].second != false
&& has[ans[k].first] == false ) {
ans[k].second = false ;
}
else if (ans[k].second != false
&& has[ans[k].first] == true ) {
has[ans[k].first] = false ;
}
}
}
int cnt = 0;
for ( int k = 0; k < ans.size(); k++) {
if (ans[k].second == true )
cnt++;
}
return cnt;
}
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;
}
|
Java
import java.util.HashMap;
class GFG
{
static int commonWords(String[] s)
{
int m, i, j;
String str;
HashMap<String, Boolean> has = new HashMap<>();
String[] ans1 = new String[ 100 ];
boolean [] ans2 = new boolean [ 100 ];
int track = 0 ;
m = s.length;
i = 0 ;
while (i < s[ 0 ].length())
{
str = "" ;
while (i < s[ 0 ].length() &&
s[ 0 ].charAt(i) != ' ' )
{
str += s[ 0 ].charAt(i);
i++;
}
i++;
if (str.compareTo( "" ) != 0 )
{
ans1[track] = str;
ans2[track] = true ;
track++;
}
}
for (j = 1 ; j < m; j++)
{
has.clear();
i = 0 ;
while (i < s[j].length())
{
str = "" ;
while (i < s[j].length() &&
s[j].charAt(i) != ' ' )
{
str += s[j].charAt(i);
i++;
}
i++;
if (str.compareTo( "" ) != 0 )
has.put(str, true );
}
for ( int k = 0 ; k < track; k++)
{
if (ans2[k] != false &&
!has.containsKey(ans1[k]))
ans2[k] = false ;
else if (ans2[k] != false &&
has.containsKey(ans1[k]) &&
has.get(ans1[k]) == true )
has.put(ans1[k], false );
}
}
int cnt = 0 ;
for ( int k = 0 ; k < track; k++)
if (ans2[k] == true )
cnt++;
return cnt;
}
public static void main(String[] args)
{
String[] s = { "there is a cow" , "cow is our mother" ,
"cow gives us milk and milk is sweet" ,
"there is a boy who loves cow" };
System.out.println(commonWords(s));
}
}
|
Python3
from collections import defaultdict
def commonWords(S):
has = defaultdict( lambda : False )
ans = []
m = len (S)
i = 0
while i < len (S[ 0 ]):
string = ""
while i < len (S[ 0 ]) and S[ 0 ][i] ! = ' ' :
string + = S[ 0 ][i]
i + = 1
i + = 1
if string ! = "":
ans.append([string, True ])
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
for k in range ( 0 , len (ans)):
if (ans[k][ 1 ] ! = False and
has[ans[k][ 0 ]] = = False ):
ans[k][ 1 ] = False
elif (ans[k][ 1 ] ! = False
and has[ans[k][ 0 ]] = = True ):
has[ans[k][ 0 ]] = False
cnt = 0
for k in range ( 0 , len (ans)):
if ans[k][ 1 ] = = True :
cnt + = 1
return cnt
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))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int commonWords(String[] s)
{
int m, i, j;
String str;
Dictionary<String,
Boolean> has =
new Dictionary<String,
Boolean>();
String[] ans1 = new String[100];
bool [] ans2 = new bool [100];
int track = 0;
m = s.Length;
i = 0;
while (i < s[0].Length)
{
str = "" ;
while (i < s[0].Length &&
s[0][i] != ' ' )
{
str += s[0][i];
i++;
}
i++;
if (str.CompareTo( "" ) != 0)
{
ans1[track] = str;
ans2[track] = true ;
track++;
}
}
for (j = 1; j < m; j++)
{
has.Clear();
i = 0;
while (i < s[j].Length)
{
str = "" ;
while (i < s[j].Length &&
s[j][i] != ' ' )
{
str += s[j][i];
i++;
}
i++;
if (str.CompareTo( "" ) != 0)
has[str] = true ;
}
for ( int k = 0; k < track; k++)
{
if (ans2[k] != false &&
!has.ContainsKey(ans1[k]))
ans2[k] = false ;
else if (ans2[k] != false &&
has.ContainsKey(ans1[k]) &&
has[ans1[k]] == true )
has[ans1[k]] = false ;
}
}
int cnt = 0;
for ( int k = 0; k < track; k++)
if (ans2[k] == true )
cnt++;
return cnt;
}
public static void Main(String[] args)
{
String[] s = { "there is a cow" ,
"cow is our mother" ,
"cow gives us milk" +
"and milk is sweet" ,
"there is a boy who" +
"loves cow" };
Console.WriteLine(commonWords(s));
}
}
|
Javascript
<script>
function commonWords( s) {
var m, i, j;
var str;
var has = new Map();
var ans1 = [];
var ans2 = [];
var track = 0;
m = s.length;
i = 0;
while (i < s[0].length) {
str = "" ;
while (i < s[0].length && s[0].charAt(i) != ' ' ) {
str += s[0].charAt(i);
i++;
}
i++;
if (str !== "" ) {
ans1[track] = str;
ans2[track] = true ;
track++;
}
}
for (j = 1; j < m; j++) {
has.clear();
i = 0;
while (i < s[j].length) {
str = "" ;
while (i < s[j].length && s[j].charAt(i) != ' ' ) {
str += s[j].charAt(i);
i++;
}
i++;
if (str !== "" )
has.set(str, true );
}
for (k = 0; k < track; k++) {
if (ans2[k] != false && !has.has(ans1[k]))
ans2[k] = false ;
else if (ans2[k] != false && has.has(ans1[k]) && has.get(ans1[k]) == true )
has.set(ans1[k], false );
}
}
var cnt = 0;
for (k = 0; k < track; k++)
if (ans2[k] == true )
cnt++;
return cnt;
}
var s = [ "there is a cow" , "cow is our mother" , "cow gives us milk and milk is sweet" ,
"there is a boy who loves cow" ];
document.write(commonWords(s));
</script>
|
The time complexity of the given implementation is O(nmk), where n is the average length of a sentence, m is the number of sentences, and k is the average length of a word.
The auxiliary space used by the algorithm is also O(nmk)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...