Open In App

Check if given words are present in a string

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given a big string and an array of small strings, all of which are smaller in length than the big string. The task is to create an array of booleans, where each boolean represents whether the small string at that index in the array of small strings is contained in the big string. 
Note : that you can’t use language-built-in string-matching methods. 
Examples:

Input : bigString = “this is a big string”, smallStrings = [“this”, “yo”, “is”, “a”, “bigger”, “string”, “kappa”] 
Output : [true, false, true, true, false, true, false]

 Input : bigString = “Mary goes to the shopping center every week.”, smallStrings = [“to”, “Mary”, “centers”, “shop”, “shopping”, “string”, “kappa”] 
Output : [true, true, false, true, true, false, false]

Approach : Naive Approach A simple way to solve this problem is to iterate through all of the small strings, checking if each of them is contained in the big string by iterating through the big string’s characters and comparing them to the given small string’s characters with a couple of loops. Below is the implementation of the above approach: 

C++




// Find the small string at that index in the array of
// small strings is contained in the big string
#include <bits/stdc++.h>
using namespace std;
bool isInBigString(string bigString, string smallString);
bool isInBigStringHelper(string bigString, string smallString, int startIdx);
 
// Function to the multiStringSearch
vector<bool> multiStringSearch(string bigString,
                          vector<string> smallStrings)
{
    vector<bool> solution;
 
    // iterate in the smallString
    for (string smallString : smallStrings) {
 
        // calling the isInBigString Function
        solution.push_back(isInBigString(bigString, smallString));
    }
    return solution;
}
 
// Function to the bigString
bool isInBigString(string bigString, string smallString)
{
    // iterate in the bigString
    for (int i = 0; i < bigString.length(); i++) {
 
        // Check if length of smallString + i is greater than
        // the length of bigString
        if (i + smallString.length() > bigString.length()) {
            break;
        }
 
        // call the function isInBigStringHelper
        if (isInBigStringHelper(bigString, smallString, i)) {
            return true;
        }
    }
    return false;
}
 
// Helper Function to the Finding bigString
bool isInBigStringHelper(string bigString, string smallString, int startIdx)
{
    // Initialize leftBigIdx and rightBigIdx and leftSmallIdx variables
    int leftBigIdx = startIdx;
    int rightBigIdx = startIdx + smallString.length() - 1;
    int leftSmallIdx = 0;
    int rightSmallIdx = smallString.length() - 1;
 
 
    // Iterate until leftBigIdx variable reaches less
    // than or equal to rightBigIdx
    while (leftBigIdx <= rightBigIdx) {
 
        // Check if bigString[leftBigIdx] is not equal
        // to smallString[leftSmallIdx] or Check if
        // bigString[rightBigIdx] is not equal to
        // smallString[rightSmallIdx] than return false
        // otherwise increment leftBigIdx and leftSmallIdx
        // decrement rightBigIdx and rightSmallIdx
        if (bigString[leftBigIdx] != smallString[leftSmallIdx] ||
            bigString[rightBigIdx] != smallString[rightSmallIdx]) {
            return false;
        }
 
        leftBigIdx++;
        rightBigIdx--;
        leftSmallIdx++;
        rightSmallIdx--;
    }
 
    return true;
}
 
// Driver code
int main(int argc, char* argv[])
{
    // initialize string
    string str = "this is a big string";
 
    // initialize vector string
 
    vector<string> substr = { "this", "yo", "is", "a",
                        "bigger", "string", "kappa" };
 
    // Function call
    vector<bool> ans = multiStringSearch(str, substr);
 
    // Print answers
    for (int i = 0; i < ans.size(); i++) {
 
        // Check if ans[i] is equal to 1
        // then Print true otherwise print false
        if (ans[i] == 1) {
            cout << "true"
                 << " ";
        }
        else {
            cout << "false"
                 << " ";
        }
    }
    return 0;
}


Java




// Java program to find the small string
// at that index in the array of small strings
// is contained in the big string
import java.util.*;
class multiStringSearch
{
    // Function to the bigString
    static boolean isInBigString(String bigString, String smallString)
    {
        // iterate in the bigString
        for (int i = 0; i < bigString.length(); i++)
        {
            // Check if length of smallString + i is greater than
            // the length of bigString
            if (i + smallString.length() > bigString.length())
                break;
            // call the function isInBigStringHelper
            if (isInBigStringHelper(bigString, smallString, i))
                return true;
        }
        return false;
    }
    // Helper Function to the Finding bigString
    static boolean isInBigStringHelper(String bigString,
                                String smallString, int startIdx)
    {
        // Initialize leftBigIdx and rightBigIdx and
        // leftSmallIdx variables
        int leftBigIdx = startIdx;
        int rightBigIdx = startIdx + smallString.length() - 1;
        int leftSmallIdx = 0;
        int rightSmallIdx = smallString.length() - 1;
 
        // Iterate until leftBigIdx variable reaches
        // less than or equal to rightBigIdx
        while (leftBigIdx <= rightBigIdx)
        {
            // Check if bigString[leftBigIdx] is not equal
            // to smallString[leftSmallIdx] or Check if
            // bigString[rightBigIdx] is not equal to
            // smallString[rightSmallIdx] than return false
            // otherwise increment leftBigIdx and leftSmallIdx
            // decrement rightBigIdx and rightSmallIdx
            if (bigString.charAt(leftBigIdx) != smallString.charAt(leftSmallIdx)
                    || bigString.charAt(rightBigIdx) != smallString.charAt(rightSmallIdx))
                return false;
            leftBigIdx++;
            rightBigIdx--;
            leftSmallIdx++;
            rightSmallIdx--;
        }
        return true;
    }
    // Function to the multiStringSearch
    static ArrayList<Boolean> multiStringSearch(String bigString,
                                        ArrayList<String> smallStrings)
    {
        ArrayList<Boolean> solution = new ArrayList<Boolean>();
        // iterate in the smallString
        for (String smallString : smallStrings)
        {
            // calling the isInBigString Function
            solution.add(isInBigString(bigString, smallString));
        }
        return solution;
    }
    // Driver code
    public static void main(String[] args)
    {
        // initialize string
        String str = "this is a big string";
        // initialize vector string
        ArrayList<String> substr = new ArrayList<String>(
                        Arrays.asList("this", "yo", "is",
                                    "a", "bigger", "string",
                                                        "kappa"));
        // Function call
        ArrayList<Boolean> ans = multiStringSearch(str, substr);
        // Print answers
        for (int i = 0; i < ans.size(); i++)
        {
            // Check if ans[i] is equal to 1
            // then Print true otherwise print false
            if (ans.get(i) == true)
                System.out.print("true" + " ");
            else
                System.out.print("false" + " ");
        }
    }
}


Python3




# Find the small string at that index in the array of
# small strings is contained in the big string
 
# Helper Function to the Finding bigString
def isInBigStringHelper(bigString,smallString,startIdx):
     
    # Initialize leftBigIdx and rightBigIdx and leftSmallIdx variables
    leftBigIdx = startIdx
    rightBigIdx = startIdx + len(smallString) - 1
    leftSmallIdx = 0
    rightSmallIdx = len(smallString) - 1
 
    # Iterate until leftBigIdx variable reaches less
    # than or equal to rightBigIdx
    while (leftBigIdx <= rightBigIdx):
         
        # Check if bigString[leftBigIdx] is not equal
        # to smallString[leftSmallIdx] or Check if
        # bigString[rightBigIdx] is not equal to
        # smallString[rightSmallIdx] than return false
        # otherwise increment leftBigIdx and leftSmallIdx
        # decrement rightBigIdx and rightSmallIdx
        if (bigString[leftBigIdx] != smallString[leftSmallIdx] or
            bigString[rightBigIdx] != smallString[rightSmallIdx]):
            return False
 
        leftBigIdx += 1
        rightBigIdx -= 1
        leftSmallIdx += 1
        rightSmallIdx -= 1
    return True
 
# Function to the bigString
def isInBigString(bigString, smallString):
     
    # iterate in the bigString
    for i in range(len(bigString)):
         
        # Check if length of smallString + i is greater than
        # the length of bigString
        if (i + len(smallString) > len(bigString)):
            break
 
        # call the function isInBigStringHelper
        if (isInBigStringHelper(bigString, smallString, i)):
            return True
    return False
 
# Function to the multiStringSearch
def multiStringSearch(bigString, smallStrings):
    solution = []
 
    # iterate in the smallString
    for smallString in smallStrings:
        # calling the isInBigString Function
        solution.append(isInBigString(bigString, smallString))
    return solution
 
# Driver code
if __name__ == '__main__':
    # initialize string
    str1 = "this is a big string"
 
    # initialize vector string
 
    substr = ["this", "yo", "is", "a","bigger", "string", "kappa"]
 
    # Function call
    ans = multiStringSearch(str1, substr)
 
    # Print answers
    for i in range(len(ans)):
        # Check if ans[i] is equal to 1
        # then Print true otherwise print false
        if (ans[i] == 1):
            print("true",end = " ")
        else:
            print("false",end = " ")
 
# This code is contributed by Bhupendra_Singh


C#




using System;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to find the big string
  static bool IsInBigString(string bigString,
                            string smallString)
  {
 
    // iterate in the bigString
    for (int i = 0; i < bigString.Length; i++)
    {
 
      // Check if length of smallString + i is greater
      // than the length of bigString
      if (i + smallString.Length > bigString.Length)
        break;
 
      // call the function IsInBigStringHelper
      if (IsInBigStringHelper(bigString, smallString,
                              i))
        return true;
    }
    return false;
  }
 
  // Helper Function to find the big string
  static bool IsInBigStringHelper(string bigString,
                                  string smallString,
                                  int startIdx)
  {
 
    // Initialize leftBigIdx and rightBigIdx and
    // leftSmallIdx variables
    int leftBigIdx = startIdx;
    int rightBigIdx = startIdx + smallString.Length - 1;
    int leftSmallIdx = 0;
    int rightSmallIdx = smallString.Length - 1;
 
    // Iterate until leftBigIdx variable reaches
    // less than or equal to rightBigIdx
    while (leftBigIdx <= rightBigIdx)
    {
 
      // Check if bigString[leftBigIdx] is not equal
      // to smallString[leftSmallIdx] or Check if
      // bigString[rightBigIdx] is not equal to
      // smallString[rightSmallIdx] then return false
      // otherwise increment leftBigIdx and
      // leftSmallIdx decrement rightBigIdx and
      // rightSmallIdx
      if (bigString[leftBigIdx]
          != smallString[leftSmallIdx]
          || bigString[rightBigIdx]
          != smallString[rightSmallIdx])
        return false;
      leftBigIdx++;
      rightBigIdx--;
      leftSmallIdx++;
      rightSmallIdx--;
    }
    return true;
  }
 
  // Function to perform multiStringSearch
  static List<bool>
    MultiStringSearch(string bigString,
                      List<string> smallStrings)
  {
    List<bool> solution = new List<bool>();
 
    // iterate in the smallString
    foreach(string smallString in smallStrings)
    {
 
      // calling the IsInBigString Function
      solution.Add(
        IsInBigString(bigString, smallString));
    }
    return solution;
  }
 
  // Main function
  static void Main(string[] args)
  {
    // initialize string
    string str = "this is a big string";
 
    // initialize list of strings
    List<string> substr = new List<string>(
      new string[] { "this", "yo", "is", "a",
                    "bigger", "string", "kappa" });
 
    // Function call
    List<bool> ans = MultiStringSearch(str, substr);
 
    // Print answers
    foreach(bool b in ans)
    {
 
      // Check if ans[i] isequal to true
      // then print true otherwise print false
      Console.Write(b ? "true" : "false");
      Console.Write( " ");
    }
  }
}


Javascript




       // JavaScript code for the above approach
       // Find the small string at that index in the array of
       // small strings is contained in the big string
 
       // Helper Function to the Finding bigString
       function isInBigStringHelper(bigString, smallString, startIdx)
       {
        
           // Initialize leftBigIdx and rightBigIdx and leftSmallIdx variables
           let leftBigIdx = startIdx;
           let rightBigIdx = startIdx + smallString.length - 1;
           let leftSmallIdx = 0;
           let rightSmallIdx = smallString.length - 1;
 
           // Iterate until leftBigIdx variable reaches less
           // than or equal to rightBigIdx
           while (leftBigIdx <= rightBigIdx)
           {
            
               // Check if bigString[leftBigIdx] is not equal
               // to smallString[leftSmallIdx] or Check if
               // bigString[rightBigIdx] is not equal to
               // smallString[rightSmallIdx] than return false
               // otherwise increment leftBigIdx and leftSmallIdx
               // decrement rightBigIdx and rightSmallIdx
               if (
                   bigString[leftBigIdx] !== smallString[leftSmallIdx] ||
                   bigString[rightBigIdx] !== smallString[rightSmallIdx]
               ) {
                   return false;
               }
               leftBigIdx += 1;
               rightBigIdx -= 1;
               leftSmallIdx += 1;
               rightSmallIdx -= 1;
           }
           return true;
       }
 
       // Function to the bigString
       function isInBigString(bigString, smallString)
       {
        
           // iterate in the bigString
           for (let i = 0; i < bigString.length; i++)
           {
            
               // Check if length of smallString + i is greater than
               // the length of bigString
               if (i + smallString.length > bigString.length) {
                   break;
               }
 
               // call the function isInBigStringHelper
               if (isInBigStringHelper(bigString, smallString, i)) {
                   return true;
               }
           }
           return false;
       }
 
       // Function to the multiStringSearch
       function multiStringSearch(bigString, smallStrings) {
           const solution = [];
 
           // iterate in the smallString
           for (const smallString of smallStrings)
           {
            
               // calling the isInBigString Function
               solution.push(isInBigString(bigString, smallString));
           }
           return solution;
       }
 
       // Driver code
       // initialize string
       const str1 = "this is a big string";
 
       // initialize vector string
       const substr = ["this", "yo", "is", "a", "bigger", "string", "kappa"];
 
       // Function call
       const ans = multiStringSearch(str1, substr);
 
       // Print answers
       for (let i = 0; i < ans.length; i++)
       {
        
           // Check if ans[i] is equal to 1
           // then Print true otherwise print false
           if (ans[i] == 1) {
               console.log("true", end = " ");
           } else {
               console.log("false", end = " ");
           }
       }
 
// This code is contributed by Potta Lokesh.


Output

true false true true false true false 








Time Complexity : O(b * n * s), where b is the length of the bigstring and n is the number of small strings and s is the length of longest small string. 
Auxiliary Space : O(n)

 Approach : Using Suffix Trie Build a Suffix-trie data structure containing all of the big string’s suffixes. Then, iterate through all of the small strings and check if each of them is contained in the data structure you have created. Below is the implementation of the above approach: 

CPP




// Find the small string at that index in the array of
// small strings is contained in the big string
#include <bits/stdc++.h>
using namespace std;
// Blueprint of the TrieNode
class TrieNode {
public:
 
    // Declaring children to be of <char, TrieNode> type
    // key will be of char type and mapped value will
    // be of TrieNode type
    unordered_map<char, TrieNode*> children;
};
 
// Blueprint of the ModifiedSuffixTrie
class ModifiedSuffixTrie {
public:
    TrieNode* root;
    ModifiedSuffixTrie(string str)
    {
        this->root = new TrieNode();
 
        // Function call
        this->populateModifiedSuffixTrieFrom(str);
    }
 
    void populateModifiedSuffixTrieFrom(string str)
    {
        // iterate in the length of String
        for (int i = 0; i < str.length(); i++) {
 
            // Function call
            this->insertSubstringStartingAt(i, str);
        }
    }
 
    void insertSubstringStartingAt(int i, string str)
    {
        TrieNode* node = this->root;
 
        // iterate in the length of String
        for (int j = i; j < str.length(); j++) {
 
            // initialize char as a letter
            // put the value of str[j] in letter
            char letter = str[j];
 
            // Check if letter is equal to endnode or not
            if (node->children.find(letter) == node->children.end()) {
                TrieNode* newNode = new TrieNode();
                node->children.insert({ letter, newNode });
            }
            node = node->children[letter];
        }
    }
 
    bool contains(string str)
    {
        TrieNode* node = this->root;
 
        // iterate in the String
        for (char letter : str) {
 
            // Check if letter is equal to endnode or not
            if (node->children.find(letter) == node->children.end()) {
                return false;
            }
            node = node->children[letter];
        }
        return true;
    }
};
 
// Function to the multiStringSearch
vector<bool> multiStringSearch(string bigString, vector<string> smallStrings)
{
    ModifiedSuffixTrie modifiedSuffixTrie(bigString);
    vector<bool> solution;
 
    // iterate in the smallString
    for (string smallString : smallStrings) {
        solution.push_back(modifiedSuffixTrie.contains(smallString));
    }
    return solution;
}
 
// Driver code
int main(int argc, char* argv[])
{
    // initialize string
    string str = "this is a big string";
 
    // initialize vector string
    vector<string> substr = { "this", "yo", "is", "a",
                        "bigger", "string", "kappa" };
 
    // Function call
    vector<bool> ans = multiStringSearch(str, substr);
 
    // Print answers
    for (int i = 0; i < ans.size(); i++) {
 
        // Check if ans[i] is equal to 1
        // then Print true otherwise print false
        if (ans[i] == 1) {
            cout << "true"
                << " ";
        }
        else {
            cout << "false"
                << " ";
        }
    }
    return 0;
}


Java




// Java program to find the small string at that index in
// the array of small strings is contained in the big string
 
import java.io.*;
import java.util.*;
 
// Blueprint of the TrieNode
class TrieNode {
    // Declaring children to be of <char, TrieNode> type key
    // will be of char type and mapped value will be of
    // TrieNode type
    Map<Character, TrieNode> children;
 
    TrieNode() { this.children = new HashMap<>(); }
}
 
// Blueprint of the ModifiedSuffixTrie
class ModifiedSuffixTrie {
    TrieNode root;
 
    ModifiedSuffixTrie(String str)
    {
        this.root = new TrieNode();
 
        // Function call
        this.populateModifiedSuffixTrieFrom(str);
    }
 
    void populateModifiedSuffixTrieFrom(String str)
    {
        // iterate in the length of String
        for (int i = 0; i < str.length(); i++) {
 
            // Function call
            this.insertSubstringStartingAt(i, str);
        }
    }
 
    void insertSubstringStartingAt(int i, String str)
    {
        TrieNode node = this.root;
 
        // iterate in the length of String
        for (int j = i; j < str.length(); j++) {
 
            // initialize char as a letter put the value of
            // str[j] in letter
            char letter = str.charAt(j);
 
            // Check if letter is equal to endnode or not
            if (!node.children.containsKey(letter)) {
                TrieNode newNode = new TrieNode();
                node.children.put(letter, newNode);
            }
            node = node.children.get(letter);
        }
    }
 
    boolean contains(String str)
    {
        TrieNode node = this.root;
 
        // iterate in the String
        for (char letter : str.toCharArray()) {
 
            // Check if letter is equal to endnode or not
            if (!node.children.containsKey(letter)) {
                return false;
            }
            node = node.children.get(letter);
        }
        return true;
    }
}
 
class GFG {
 
    // Function to the multiStringSearch
    public static List<Boolean>
    multiStringSearch(String bigString,
                      List<String> smallStrings)
    {
        ModifiedSuffixTrie modifiedSuffixTrie
            = new ModifiedSuffixTrie(bigString);
        List<Boolean> solution = new ArrayList<>();
 
        // iterate in the smallString
        for (String smallString : smallStrings) {
            solution.add(
                modifiedSuffixTrie.contains(smallString));
        }
        return solution;
    }
 
    public static void main(String[] args)
    {
        // initialize string
        String str = "this is a big string";
 
        // initialize list of strings
        List<String> substr
            = Arrays.asList("this", "yo", "is", "a",
                            "bigger", "string", "kappa");
 
        // Function call
        List<Boolean> ans = multiStringSearch(str, substr);
 
        // Print answers
        for (boolean bool : ans) {
            System.out.print(bool + " ");
        }
    }
}
 
// This code is contributed by karthik


Python3




# python code implementation for the above approach
 
# Blueprint of the TrieNode
class TrieNode:
    def __init__(self):
        # Declaring children to be of <char, TrieNode> type, key will be of char
        # type and mapped value will be of TrieNode type
        self.children = {}
 
# Blueprint of the ModifiedSuffixTrie
class ModifiedSuffixTrie:
    def __init__(self, string):
        self.root = TrieNode()
        # Function call
        self.populateModifiedSuffixTrieFrom(string)
 
    def populateModifiedSuffixTrieFrom(self, string):
        # iterate in the length of String
        for i in range(len(string)):
            # Function call
            self.insertSubstringStartingAt(i, string)
 
    def insertSubstringStartingAt(self, i, string):
        node = self.root
        # iterate in the length of String
        for j in range(i, len(string)):
            # initialize char as a letter put the value of string[j] in letter
            letter = string[j]
            # Check if letter is equal to endnode or not
            if letter not in node.children:
                newNode = TrieNode()
                node.children[letter] = newNode
            node = node.children[letter]
 
    def contains(self, string):
        node = self.root
        # iterate in the String
        for letter in string:
            # Check if letter is equal to endnode or not
            if letter not in node.children:
                return False
            node = node.children[letter]
        return True
 
# Function to the multiStringSearch
def multiStringSearch(bigString, smallStrings):
    modifiedSuffixTrie = ModifiedSuffixTrie(bigString)
    solution = []
    # iterate in the smallString
    for smallString in smallStrings:
        solution.append(modifiedSuffixTrie.contains(smallString))
    return solution
 
 
# initialize string
string = "this is a big string"
 
# initialize list of strings
small_strings = ["this", "yo", "is", "a", "bigger", "string", "kappa"]
 
# Function call
ans = multiStringSearch(string, small_strings)
 
# Print answers
for bool_val in ans:
    print(bool_val, end=' ')
 
# This code is contributed by lokesh.


C#




// C# program to find the small string at that index in the
// array of small strings is contained in the big string
using System;
using System.Collections.Generic;
 
// Blueprint of the TrieNode
class TrieNode {
 
  // Declaring children to be of <char, TrieNode> type key
  // will be of char type and mapped value will be of
  // TrieNode type
  public Dictionary<char, TrieNode> children;
 
  public TrieNode()
  {
    this.children = new Dictionary<char, TrieNode>();
  }
}
 
// Blueprint of the ModifiedSuffixTrie
class ModifiedSuffixTrie {
  public TrieNode root;
 
  public ModifiedSuffixTrie(string str)
  {
    this.root = new TrieNode();
 
    // Function call
    this.populateModifiedSuffixTrieFrom(str);
  }
 
  public void populateModifiedSuffixTrieFrom(string str)
  {
    // iterate in the length of String
    for (int i = 0; i < str.Length; i++) {
      // Function call
      this.insertSubstringStartingAt(i, str);
    }
  }
 
  public void insertSubstringStartingAt(int i, string str)
  {
    TrieNode node = this.root;
 
    // iterate in the length of String
    for (int j = i; j < str.Length; j++) {
      // initialize char as a letter put the value of
      // str[j] in letter
      char letter = str[j];
 
      // Check if letter is equal to endnode or not
      if (!node.children.ContainsKey(letter)) {
        TrieNode newNode = new TrieNode();
        node.children.Add(letter, newNode);
      }
      node = node.children[letter];
    }
  }
 
  public bool contains(string str)
  {
    TrieNode node = this.root;
 
    // iterate in the String
    foreach(char letter in str)
    {
      // Check if letter is equal to endnode or not
      if (!node.children.ContainsKey(letter)) {
        return false;
      }
      node = node.children[letter];
    }
    return true;
  }
}
 
public class GFG {
 
  // Function to the multiStringSearch
  public static List<bool>
    multiStringSearch(string bigString,
                      List<string> smallStrings)
  {
    ModifiedSuffixTrie modifiedSuffixTrie
      = new ModifiedSuffixTrie(bigString);
    List<bool> solution = new List<bool>();
 
    // iterate in the smallString
    foreach(string smallString in smallStrings)
    {
      solution.Add(
        modifiedSuffixTrie.contains(smallString));
    }
    return solution;
  }
 
  static public void Main()
  {
 
    // Code
    // initialize string
    string str = "this is a big string";
 
    // initialize list of strings
    List<string> substr
      = new List<string>{ "this", "yo",     "is",
                         "a",    "bigger", "string",
                         "kappa" };
 
    // Function call
    List<bool> ans = multiStringSearch(str, substr);
 
    // Print answers
    foreach(bool b in ans) { Console.Write(b + " "); }
  }
}
 
// This code is contributed by sankar.


Javascript




// Blueprint of the TrieNode
class TrieNode {
    constructor() {
        // Declaring children to be of Map<char, TrieNode> type
        // key will be of char type and mapped value will
        // be of TrieNode type
        this.children = new Map();
    }
}
 
// Blueprint of the ModifiedSuffixTrie
class ModifiedSuffixTrie {
    constructor(str) {
        this.root = new TrieNode();
         
        // Function call
        this.populateModifiedSuffixTrieFrom(str);
    }
 
    populateModifiedSuffixTrieFrom(str)
    {
     
        // iterate in the length of String
        for (let i = 0; i < str.length; i++)
        {
         
            // Function call
            this.insertSubstringStartingAt(i, str);
        }
    }
 
    insertSubstringStartingAt(i, str) {
        let node = this.root;
         
        // iterate in the length of String
        for (let j = i; j < str.length; j++)
        {
         
            // initialize char as a letter
            // put the value of str[j] in letter
            const letter = str[j];
 
            // Check if letter is equal to endnode or not
            if (!node.children.has(letter)) {
                const newNode = new TrieNode();
                node.children.set(letter, newNode);
            }
            node = node.children.get(letter);
        }
    }
 
    contains(str) {
        let node = this.root;
        // iterate in the String
        for (const letter of str) {
            // Check if letter is equal to endnode or not
            if (!node.children.has(letter)) {
                return false;
            }
            node = node.children.get(letter);
        }
        return true;
    }
}
 
// Function to the multiStringSearch
function multiStringSearch(bigString, smallStrings) {
    const modifiedSuffixTrie = new ModifiedSuffixTrie(bigString);
    const solution = [];
 
    // iterate in the smallString
    for (const smallString of smallStrings) {
        solution.push(modifiedSuffixTrie.contains(smallString));
    }
    return solution;
}
 
// Driver code
const bigString = "this is a big string";
const smallStrings = [
    "this",
    "yo",
    "is",
    "a",
    "bigger",
    "string",
    "kappa",
];
 
// Function call
const ans = multiStringSearch(bigString, smallStrings);
 
// Print answers
for (let i = 0; i < ans.length; i++)
{
 
    // Check if ans[i] is equal to 1
    // then Print true otherwise print false
    if (ans[i]) {
        console.log("true");
    } else {
        console.log("false");
    }
}
 
// This code is contributed by sarojmcy2e


Output

true false true true false true false 








Time Complexity : O(b*b + n * s), where b is the length of the bigstring and n is the number of small strings and s is the length of longest small string. 
Auxiliary Space : O(b*2 + n) 
Approach : Using Trie Try building a trie containing all of the small strings. Then, iterate through the big string’s characters and check if any part of the big string is a string contained in the trie you have created. Below is the implementation of the above approach: 

CPP




// Find the small string at that index in the array of
// small strings is contained in the big string
#include <bits/stdc++.h>
using namespace std;
 
// Blueprint of the TrieNode
class TrieNode {
public:
 
    // Declaring children to be of <char, TrieNode> type
    // key will be of char type and mapped value will
    // be of TrieNode type
    unordered_map<char, TrieNode*> children;
    string word;
};
 
// Blueprint of the Trie
class Trie {
public:
    TrieNode* root;
    char endSymbol;
    Trie()
    {
        this->root = new TrieNode();
        this->endSymbol = '*';
    }
 
    // function to insert string
    void insert(string str)
    {
        TrieNode* current = this->root;
 
        // iterate in the length of String
        for (int i = 0; i < str.length(); i++) {
 
            // initialize char as a letter
            // put the value of str[i] in letter
            char letter = str[i];
 
            // Check if letter is equal to endnode or not
            if (current->children.find(letter) == current->children.end()) {
                TrieNode* newNode = new TrieNode();
                current->children.insert({ letter, newNode });
            }
            current = current->children[letter];
        }
        current->children.insert({ this->endSymbol, NULL });
        current->word = str;
    }
};
 
// define a findSmallStringsIn function
void findSmallStringsIn(string str, int startIdx, Trie* trie,
                unordered_map<string, bool>* containedStrings);
 
// Function to the multiStringSearch
vector<bool> multiStringSearch(string bigString, vector<string> smallStrings)
{
    Trie* trie = new Trie();
 
    // iterate in the smallString
    for (string smallString : smallStrings) {
        trie->insert(smallString);
    }
 
    // Declaring containedStrings to be of <string, bool> type
    // key will be of string type and mapped value will
    // be of boolean type
    unordered_map<string, bool> containedStrings;
 
    // iterate in the bigString
    for (int i = 0; i < bigString.length(); i++) {
        findSmallStringsIn(bigString, i, trie, &containedStrings);
    }
 
    vector<bool> solution;
 
    // iterate in the smallString
    for (string smallString : smallStrings) {
        solution.push_back(containedStrings.find(smallString)
                                != containedStrings.end());
    }
    return solution;
}
 
// Function to findSmallStringsIn
void findSmallStringsIn(string str, int startIdx,
    Trie* trie, unordered_map<string, bool>* containedStrings)
{
    TrieNode* currentNode = trie->root;
 
    // iterate the length of the string
    for (int i = startIdx; i < str.length(); i++) {
 
        // Check if letter is equal to endnode or not
        if (currentNode->children.find(str[i]) ==
                        currentNode->children.end()) {
            break;
        }
        currentNode = currentNode->children[str[i]];
 
        if (currentNode->children.find(trie->endSymbol) !=
                            currentNode->children.end()) {
            containedStrings->insert({ currentNode->word, true });
        }
    }
}
 
// Driver code
int main(int argc, char* argv[])
{
    // initialize string
    string str = "this is a big string";
 
    // initialize vector string
    vector<string> substr = { "this", "yo", "is", "a",
                        "bigger", "string", "kappa" };
 
    // Function call
    vector<bool> ans = multiStringSearch(str, substr);
 
    // Print answers
    for (int i = 0; i < ans.size(); i++) {
 
        // Check if ans[i] is equal to 1
        // then Print true otherwise print false
        if (ans[i] == 1) {
            cout << "true"
                << " ";
        }
        else {
            cout << "false"
                << " ";
        }
    }
    return 0;
}


Java




import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
class TrieNode {
    Map<Character, TrieNode> children;
    String word;
 
    TrieNode() {
        children = new HashMap<>();
        word = "";
    }
}
 
class Trie {
    TrieNode root;
    char endSymbol;
 
    Trie() {
        root = new TrieNode();
        endSymbol = '*';
    }
 
    // Function to insert a string into the Trie
    void insert(String str) {
        TrieNode current = root;
        for (int i = 0; i < str.length(); i++) {
            char letter = str.charAt(i);
            if (!current.children.containsKey(letter)) {
                TrieNode newNode = new TrieNode();
                current.children.put(letter, newNode);
            }
            current = current.children.get(letter);
        }
        current.children.put(endSymbol, null); // Mark the end of the word
        current.word = str; // Store the word associated with this node
    }
}
 
public class MultiStringSearch {
    // Function to find small strings in the big string
    static void findSmallStringsIn(String str, int startIdx,
                                   Trie trie,
                                   Map<String, Boolean> containedStrings) {
        TrieNode currentNode = trie.root;
        for (int i = startIdx; i < str.length(); i++) {
            if (!currentNode.children.containsKey(str.charAt(i))) {
                break; // No match found, break the loop
            }
            currentNode = currentNode.children.get(str.charAt(i));
            if (currentNode.children.containsKey(trie.endSymbol)) {
                containedStrings.put(currentNode.word, true); // Found a small string,
                                                              // mark it as contained
            }
        }
    }
 
    // Function to search for small strings in a big string
    static List<Boolean> multiStringSearch(String bigString, List<String> smallStrings) {
        Trie trie = new Trie();
        for (String smallString : smallStrings) {
            trie.insert(smallString); // Build the Trie with small strings
        }
 
        Map<String, Boolean> containedStrings = new HashMap<>();
        for (int i = 0; i < bigString.length(); i++) {
            findSmallStringsIn(bigString, i, trie, containedStrings); // Search for small strings in
                                                                      // the big string
        }
 
        List<Boolean> solution = new ArrayList<>();
        for (String smallString : smallStrings) {
            solution.add(containedStrings.containsKey(smallString)); // Check if each small
                                                                     // string is contained
        }
        return solution;
    }
 
    public static void main(String[] args) {
        String bigString = "this is a big string";
        List<String> smallStrings = List.of("this", "yo", "is", "a", "bigger", "string", "kappa");
 
        List<Boolean> ans = multiStringSearch(bigString, smallStrings);
 
        for (Boolean isContained : ans) {
            System.out.print(isContained + " ");
        }
    }
}


Python3




class TrieNode:
    def __init__(self):
        self.children = {}
        self.word = ""
 
class Trie:
    def __init__(self):
        self.root = TrieNode()
        self.endSymbol = '*'
 
    def insert(self, string):
        current = self.root
        for letter in string:
            if letter not in current.children:
                current.children[letter] = TrieNode()
            current = current.children[letter]
        current.children[self.endSymbol] = None
        current.word = string
 
def find_small_strings_in(string, start_idx, trie, contained_strings):
    current_node = trie.root
    for i in range(start_idx, len(string)):
        if string[i] not in current_node.children:
            break
        current_node = current_node.children[string[i]]
        if trie.endSymbol in current_node.children:
            contained_strings[current_node.word] = True
 
def multi_string_search(big_string, small_strings):
    trie = Trie()
    for small_string in small_strings:
        trie.insert(small_string)
 
    contained_strings = {}
    for i in range(len(big_string)):
        find_small_strings_in(big_string, i, trie, contained_strings)
 
    solution = [contained_strings.get(small_string, False) for small_string in small_strings]
    return solution
 
def main():
    big_string = "this is a big string"
    small_strings = ["this", "yo", "is", "a", "bigger", "string", "kappa"]
 
    ans = multi_string_search(big_string, small_strings)
 
    for is_contained in ans:
        print(is_contained, end=" ")
 
if __name__ == "__main__":
    main()
 
     
     
# code contributed by Siddhesh


C#




using System;
using System.Collections.Generic;
 
// Blueprint of the TrieNode
public class TrieNode
{
    // Declaring children to be of <char, TrieNode> type
    // key will be of char type and mapped value will
    // be of TrieNode type
    public Dictionary<char, TrieNode> Children;
    public string Word;
 
    public TrieNode()
    {
        Children = new Dictionary<char, TrieNode>();
        Word = "";
    }
}
 
// Blueprint of the Trie
public class Trie
{
    public TrieNode Root;
    public char EndSymbol;
 
    public Trie()
    {
        Root = new TrieNode();
        EndSymbol = '*';
    }
 
    // function to insert string
    public void Insert(string str)
    {
        TrieNode current = Root;
 
        // iterate in the length of String
        for (int i = 0; i < str.Length; i++)
        {
            // initialize char as a letter
            // put the value of str[i] in letter
            char letter = str[i];
 
            // Check if letter is equal to endnode or not
            if (!current.Children.ContainsKey(letter))
            {
                TrieNode newNode = new TrieNode();
                current.Children.Add(letter, newNode);
            }
 
            current = current.Children[letter];
        }
 
        current.Children.Add(EndSymbol, null);
        current.Word = str;
    }
}
 
public class TrieSearch
{
    // define a FindSmallStringsIn function
    private static void FindSmallStringsIn(string str, int startIdx, Trie trie,
                                    Dictionary<string, bool> containedStrings)
    {
        TrieNode currentNode = trie.Root;
 
        // iterate the length of the string
        for (int i = startIdx; i < str.Length; i++)
        {
            // Check if letter is equal to endnode or not
            if (!currentNode.Children.ContainsKey(str[i]))
            {
                break;
            }
 
            currentNode = currentNode.Children[str[i]];
 
            if (currentNode.Children.ContainsKey(trie.EndSymbol))
            {
                containedStrings[currentNode.Word] = true;
            }
        }
    }
 
    // Function to the MultiStringSearch
    public static List<bool> MultiStringSearch(string bigString, List<string> smallStrings)
    {
        Trie trie = new Trie();
 
        // iterate in the smallStrings
        foreach (string smallString in smallStrings)
        {
            trie.Insert(smallString);
        }
 
        // Declaring containedStrings to be of <string, bool> type
        // key will be of string type and mapped value will
        // be of boolean type
        Dictionary<string, bool> containedStrings = new Dictionary<string, bool>();
 
        // iterate in the bigString
        for (int i = 0; i < bigString.Length; i++)
        {
            FindSmallStringsIn(bigString, i, trie, containedStrings);
        }
 
        List<bool> solution = new List<bool>();
 
        // iterate in the smallStrings
        foreach (string smallString in smallStrings)
        {
            solution.Add(containedStrings.ContainsKey(smallString));
        }
 
        return solution;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        // initialize string
        string str = "this is a big string";
 
        // initialize list of strings
        List<string> substr = new List<string> { "this", "yo", "is", "a", "bigger", "string", "kappa" };
 
        // Function call
        List<bool> ans = MultiStringSearch(str, substr);
 
        // Print answers
        foreach (bool isContained in ans)
        {
            Console.Write(isContained ? "true " : "false ");
        }
    }
}


Javascript




// Blueprint of the TrieNode
class TrieNode {
    constructor() {
        this.children = new Map();
        this.word = "";
    }
}
// Blueprint of the Trie
class Trie {
    constructor() {
        this.root = new TrieNode();
        this.endSymbol = '*';
    }
    // Function to insert a string into Trie
    insert(str) {
        let current = this.root;
        // Iterate through the characters of string
        for (let i = 0; i < str.length; i++) {
            let letter = str[i];
            // Check if the letter is already a child of current node
            if (!current.children.has(letter)) {
                let newNode = new TrieNode();
                current.children.set(letter, newNode);
            }
            current = current.children.get(letter);
        }
        current.children.set(this.endSymbol, null);
        current.word = str;  // Store the complete word at the end node
    }
}
// Function to find small strings in big string
function GFG(str, startIdx, trie, containedStrings) {
    let currentNode = trie.root;
    // Iterate through the characters of the big string starting from given index
    for (let i = startIdx; i < str.length; i++) {
        // Check if the current character is a child ofcurrent node
        if (!currentNode.children.has(str[i])) {
            break// If not, break the loop
        }
        currentNode = currentNode.children.get(str[i]);
        // If the current node marks the end of a word
        // add it to the containedStrings map
        if (currentNode.children.has(trie.endSymbol)) {
            containedStrings[currentNode.word] = true;
        }
    }
}
// Function to perform multi-string search in the big string
function multiStringSearch(bigString, smallStrings) {
    let trie = new Trie();
    // Insert each small string into the Trie
    for (let smallString of smallStrings) {
        trie.insert(smallString);
    }
    let containedStrings = {};
    // Iterate through the big string to the find small strings
    for (let i = 0; i < bigString.length; i++) {
        GFG(bigString, i, trie, containedStrings);
    }
    let solution = [];
    // Check for each small string if it is contained in big string
    for (let smallString of smallStrings) {
        solution.push(containedStrings.hasOwnProperty(smallString));
    }
    return solution;
}
// Driver code
let bigString = "this is a big string";
let smallStrings = ["this", "yo", "is", "a", "bigger", "string", "kappa"];
let ans = multiStringSearch(bigString, smallStrings);
// Concatenate answers in the single string
let output = ans.map(result => result.toString()).join(" ");
// Print the output
console.log(output);


Output :

true false true true false true false

Time Complexity : O(n*s + b * s), where b is the length of the bigstring and n is the number of small strings and s is the length of longest small string. 
Auxiliary Space : O(ns)

Python3 approach using find() method

C++




#include<bits/stdc++.h>
 
using namespace std;
 
int main(){
    string bigString = "this is a big string";
    vector<string> smallStrings = {"this", "yo", "is", "a", "bigger", "string", "kappa"};
    vector<bool> x;
    for(int i = 0; i < smallStrings.size(); i++){
        if(bigString.find(smallStrings[i]) != -1){
            x.push_back(true);
        }
        else{
            x.push_back(false);
        }
    }
    for(int i = 0; i < x.size(); i++){
        cout<<x[i]<<" ";
    }
    return 0;
}


Java




// Java code to check whether a word is present in a string or not
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        String bigString = "this is a big string";
        List<String> smallStrings = Arrays.asList("this", "yo", "is", "a", "bigger", "string", "kappa");
        List<Boolean> x = new ArrayList<>();
        for (int i = 0; i < smallStrings.size(); i++) {
            if (bigString.indexOf(smallStrings.get(i)) != -1) {
                x.add(true);
            } else {
                x.add(false);
            }
        }
        for (int i = 0; i < x.size(); i++) {
            System.out.print(x.get(i) + " ");
        }
    }
}
 
// This code is contributed by Utkarsh Kumar.


Python3




# python code to check whether a word is present in a string or not
bigString = "this is a big string"
smallStrings = ["this", "yo", "is", "a", "bigger", "string", "kappa"]
x = []
# find() - returns position of specified value or else returns -1
for i in smallStrings:
  if(bigString.find(i) != -1):
    x.append(True)
  else:
    x.append(False)
print(x)


C#




// C# code to check whether a word is present in a string or
// not
 
using System;
using System.Collections.Generic;
using System.Linq;
 
public class GFG {
 
    static public void Main()
    {
 
        // Code
        string bigString = "this is a big string";
        List<string> smallStrings
            = new List<string>{ "this", "yo",     "is",
                                "a",    "bigger", "string",
                                "kappa" };
        List<bool> x = new List<bool>();
        for (int i = 0; i < smallStrings.Count; i++) {
            if (bigString.IndexOf(smallStrings[i]) != -1) {
                x.Add(true);
            }
            else {
                x.Add(false);
            }
        }
        for (int i = 0; i < x.Count; i++) {
            Console.Write(x[i] + " ");
        }
    }
}
 
// This code is contributed by sankar.


Javascript




let bigString = "this is a big string";
let smallStrings = ["this", "yo", "is", "a", "bigger", "string", "kappa"];
let x = [];
for(let i = 0; i < smallStrings.length; i++){
    if(bigString.indexOf(smallStrings[i]) != -1){
        x.push(true);
    }
    else{
        x.push(false);
    }
}
for(let i = 0; i < x.length; i++){
    console.log(x[i] + " ");
}


Output

[True, False, True, True, False, True, False]










Last Updated : 11 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads