Given two string str1 and str2, the task is to find the longest prefix of str1 which is present as a substring of the string str2. Print the prefix if possible else print -1.
Input: str1 = “geeksfor”, str2 = “forgeeks”
All the prefixes of str1 which are present in str2
are “g”, “ge”, “gee”, “geek” and “geeks”.
Input: str1 = “abc”, str2 = “def”
Approach: Check whether str1 is present as a substring in str2. If yes then str1 is the required string else remove the last character from str1 and repeat these steps until either the string str1 becomes empty or the required string is found.
Below is the implementation of the above approach:
Time Complexity: O(N * M) where N, M are the lengths of given strings.
- Maximum number of times str1 appears as a non-overlapping substring in str2
- Count of characters in str1 such that after deleting anyone of them str1 becomes str2
- Check whether str1 can be converted to str2 with the given operations
- Minimum cost to convert str1 to str2 with the given operations
- Generate all possible strings such that char at index i is either str1[i] or str2[i]
- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- Largest substring with same Characters
- Lexicographically smallest and largest substring of size k
- Find if a given string can be represented from a substring by iterating the substring “n” times
- Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'th substring
- Longest prefix which is also suffix
- Prefix to Infix Conversion
- Postfix to Prefix Conversion
- Prefix to Postfix Conversion
- Longest Common Prefix using Trie
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.