Open In App

Print all strings in the given array that occur as the substring in the given string

Last Updated : 29 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of string arr[] and a string str, the task is to print all the strings in arr[] that occur as a substring in str.

Example:

Input: str ="geeksforgeeks", arr[] ={ "forg", "geek", "ek", "dog", "sfor"}
Output: 
forg
geek
ek
sfor
Explanation: The strings "forg", "geek", "ek" and "sfor" occur as a substring in str. Therefore, the required count is 4.

Input: str ="abcd", arr[] ={ "aa", "bb", "cc"}
Output: -1

 

Approach: The given problem is an implementation base problem. It can be solved by iterating over the given array of strings and for each string in arr[], check whether it occurs as a substring of str or not using the algorithm discussed in this article. Maintain a variable that stores If no string exists as a substring. In that case, print -1.

Below is the implementation of the above approach:

C++
Java Python3 C# JavaScript

Output
forg
geek
ek
sfo

Time Complexity: O(N2)
Auxiliary Space: O(1)


Next Article

Similar Reads