Check if the Word is present in Sentence or not

Easy
0/40
Average time to solve is 15m
26 upvotes
Asked in companies
AmazonWalmartIntuit

Problem statement

You have been given a sentence ‘S’ in the form of a string and a word ‘W’, you need to find whether the word is present in the given sentence or not. The word must be present as a complete string in the sentence and not a substring of some other word.

Note:

1. All the characters in the string and the word are in lowercase.
2. Length of the sentences and the words will always be greater than zero.
3. Words in the sentence will be separated by spaces.
Detailed explanation ( Input/output format, Notes, Images )

Input Format :

The first line of the input contains an integer ‘T’ denoting the number of test cases.

The first line of each test case contains the sentence ‘S’.

The second line of each test case contains the word ‘W’.

Output Format :

The only line of output of each test case should print “Yes” if the word ‘W’ is present in the sentence ‘S’, else print “No”.

The output of each test case will be printed in a separate line.

Note: You are not required to print the expected output; it has already been taken care of. Just implement the function.

Constraints :

1 <= T <= 50
1 <= |S|, |W| <= 10000

Where ‘T’ is the number of test cases, ‘S’ and ‘W’ are strings as described in the problem statement.

Time limit: 1 sec
Sample Input 1:
2
abaa ba
abaa
coding is fun
not
Sample Output 1:
Yes
No
Explanation for Sample Input 1:
For the first input,  “abaa” is present in the sentence.
For the second input, “not” is not present in the sentence.
Sample Input 2:
2
the quick brown fox
brown
welcome to coding ninjas
ninja
Sample Output 2:
Yes
No
Explanation for Sample Input 2:
For the first input, “brown” is present in the sentence.
For the second input, the word “ninja” is not present in the sentence.
Hint

Try the simplest possible way.

Approaches (2)
Brute Force

The basic idea of this approach is to check each word of the given sentence ‘S’ if it matches with the given word ‘W’.


 

Consider the following steps:

  1. Start iterating through each character of sentence string ‘S’ using a variable ‘i’ such that 0 <= ‘i’ < |S|
    • Create a string “temp” which stores the current word.
    • Add all the subsequent characters of the sentence till space is detected or if all end of the string is reached.
    • Check if the word ‘W’ matches with “temp”. Return true if it matches.
  2. After the loop ends return false because the word is not present in the sentence.
Time Complexity

O(|S|), where |S| is the length of the string.

 

Since we are iterating through the input sentence string ‘S’ once and checking if the word matches with the given word ‘W’. So the overall time complexity will be O(|S|). Please refer here for more details link

Space Complexity

O(|S|), where |S| is the length of the string.

 

Since we are using a variable to store the words of the sentence string and in the worst case, the whole string can be a single word. So the overall space complexity will be O(|S|).

Code Solution
(100% EXP penalty)
Check if the Word is present in Sentence or not
All tags
Sort by
Search icon

Interview problems

If word is present in sentence or not. Python

def findWord(s, w):

    #   Write your code here.

    if w in s.split():

        return True

    else:

        return False

2 views
0 replies
0 upvotes

Interview problems

c++

bool findWord(string &s, string &w)

{

    //  Write your code here.

    string temp;

    stringstream ss(s);

    unordered_map<string,int>mp;

    while(ss>>temp)

    {

        mp[temp]++;

    }

    for(int i =0;i<s.size();i++)

    {

        if(mp.find(w)!=mp.end())

        {

            return true;

        }

    }

    return false;

}

124 views
0 replies
0 upvotes

Interview problems

Java Easy soln

public static boolean findWord(String sentence, String word) 

    {

        //  Write your code here.

        String[] words = sentence.split(" ");

 

        // Check if the word is present in the array of words

        for (String w : words) {

            if (w.equals(word)) {

                return true;

            }

        }

 

        // If the loop completes without finding the word, return false

        return false;

    }

76 views
0 replies
0 upvotes

Interview problems

easy and simple

#include <bits/stdc++.h> 

bool findWord(string &s, string &w)

{

    int n=s.length();

    string ans="";

    int i=0;

    while(n>=0)

    {

        if(s[i]==' '|| s[i]=='\0')

        {

            if(ans==w)

            {

                return true;

            }

            ans="";

            i++;

        }

        ans+=s[i++];

        n--;

    }

    return false;

}

153 views
0 replies
1 upvote

Interview problems

easiest C++ solution without any STL and O(n) time complexity

just use a string word store the current word and compare with the given w, if present than return true else false.
#include <bits/stdc++.h> 
bool findWord(string &s, string &w)
{
	int size=s.size();
	string word=" ";
	int j=0;

	for(int i=0;i<=size;i++){	
		if(s[i]==' '||s[i]=='\0'){	
			word=s.substr(j,i-j);
			j=i+1;
			if(word==w)
				return true;
		}
	}
	return false;
}
104 views
0 replies
1 upvote

Interview problems

Check if the Word is present in Sentence or not(using Trie)

#include <bits/stdc++.h>

struct TrieNode {

  struct TrieNode *child[26];

  bool isEnd;

};

struct TrieNode *root=new TrieNode();

void insertnode(string s)

{

    struct TrieNode* temp=root;

    for(char c:s)

    {

        if(temp->child[c-'a']==NULL) 

        temp->child[c-'a']=new TrieNode();

        temp=temp->child[c-'a'];

    }

    temp->isEnd=true;

}

bool searchword(string w)

{

    struct TrieNode* temp=root;

    for(char c:w)

    {

        if(temp->child[c-'a']==NULL) return false;

        temp=temp->child[c-'a'];

    }

    if(temp->isEnd) return true;

    return false;

}

bool findWord(string &s, string &w)

{

    std::stringstream ss(s);

    std::string word;

    while (ss >> word) {

        insertnode(word);

        if(searchword(w)) return true;

    }

    return false;

}

85 views
0 replies
0 upvotes

Interview problems

100% faster solution || o(n) || easiest stl solution

bool findWord(string &s, string &w) { // Write your code here.        map<string,bool>m1 ;        int st=0 ;    int end=s.length();    int i=0 ;    for(;i<s.length();i++){                if(s[i]==' '){            int e=i-st ;            string r=s.substr(st,e);            st=i+1 ;            m1[r]=true ; //             cout<<r<<"here"<<endl ;        }    }    string r=s.substr(st,i-st);    m1[r]=true ;    if(m1.empty()){        m1[s]=true ;    }    if(m1[w]==true){        return true ;    }    else {        return false ;    }         }

 

if you want to help u with dsa problems please connect with me via LinkedIn:

https://www.linkedin.com/in/garima-jain-98a776217/

 

Check if the Word is present in Sentence or not

Implementation: HashMap

148 views
0 replies
0 upvotes

Interview problems

stringstream linear search

#include<bits/stdc++.h>

bool findWord(string &s, string &w)
{
	//	Write your code here.
    stringstream ss(s);
    string cw;
    while(ss >> cw) {
        if(cw == w)
            return true;
    }
    return false;
}

Check if the Word is present in Sentence or not

218 views
1 reply
2 upvotes

Interview problems

Java Solution

public class Solution  {

public static boolean findWord(String s, String w)  {  // Write your code here.        if(s.equals(w))return true;        int sLength=s.length();        int wLength=w.length();        int start=s.indexOf(w+" ");        int middle=s.indexOf(" "+w+" ");        int end=s.indexOf(" "+w);        if(start==0)return true;        if(middle!=-1)return true;        if(end+wLength+1==sLength)return true;        return false; } }

Check if the Word is present in Sentence or not

89 views
0 replies
0 upvotes

Interview problems

'EOFError: EOF when reading a line' why i am getting error in this code while its working in other platform

def findWord(sentence,word):
    s=sentence.split(" ")
    for i in s:
        if (i==word):
            return True
    return False
TestCases=int(input())
j=1
while TestCases>=j:
    s=input()
    word=input()
    j=j+1
if findWord(s,word):
    print("Yes")
else:
    print("No")
    

Check if the Word is present in Sentence or not

221 views
0 replies
0 upvotes
Full screen
Console