The Wayback Machine - https://web.archive.org/web/20211028212631/https://www.geeksforgeeks.org/minimum-count-of-prefixes-and-suffixes-of-a-string-required-to-form-given-string/
Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Minimum count of prefixes and suffixes of a string required to form given string

  • Last Updated : 28 Oct, 2021

Given two strings str1 and str2, the task is to find the minimum number of prefixes and suffixes of str2 required to form the string str1. If the task is not possible, return “-1”.

Example: 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: str1 = “HELLOWORLD”, str2 = “OWORLDHELL”
Output: 2
Explanation: The above string can be formed as “HELL” + “OWORLD” which are suffix and prefix of the string str2



Input: str = “GEEKSFORGEEKS”, wrd = “SFORGEEK”
Output: 3
Explanation: “GEEK” + “SFORGEEK” + “S”  

Approach: The above problem can be solved using dynamic programming. Follow the steps below to solve the problem:

  • Initialize an array dp where the ith element arr[i] will store the minimum concatenation required to form a string up to prefix index i
  • Initialize dp[0] = 0 and other values of the dp array to -1
  • Initialize a HashSet set
  • Iterate the string str1 from left to right and at every index i:
    • Add the substring from index 0 to current index i into the HashSet set
  • Iterate the string str1 from right to left and at every index i:
    • Add the substring from index i to the end index into the HashSet set
  • Check for all the substrings in the string str1 and update the dp, accordingly
  • The final answer will be stored in dp[N], where N is the length of string str1

Below is the implementation of the above approach: 

C++




// C++ implementation for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find minimum number of
// concatenation of prefix and suffix
// of str2 to make str1
int partCount(string str1, string str2)
{
  
    // Initialze a set
    unordered_set<string> set;
  
    // Initialze a temporary string
    string temp = "";
  
    int l1 = str1.length(), l2 = str2.length();
  
    // Iterate the string str2
    // from left to right
    for (int i = 0; i < l2; i++) {
  
        // Add current character
        // to string temp
        temp += str2[i];
  
        // Insert the prefix into hashset
        set.insert(temp);
    }
  
    // Re-initialize temp string
    // to empty string
    temp = "";
  
    // Iterate the string in reverse direction
    for (int i = l2 - 1; i >= 0; i--) {
  
        // Add current character to temp
        temp += str2[i];
  
        // Reverse the string temp
        reverse(temp.begin(), temp.end());
  
        // Insert the suffix into the hashet
        set.insert(temp);
  
        // Reverse the string temp again
        reverse(temp.begin(), temp.end());
    }
  
    // Initialize dp array to store the answer
    int dp[str1.length() + 1];
  
    memset(dp, -1, sizeof(dp));
    dp[0] = 0;
  
    // Check for all substrings starting
    // and ending at every indices
    for (int i = 0; i < l1; i++) {
        for (int j = 1; j <= l1 - i; j++) {
  
            // HashSet contains the substring
            if (set.count(str1.substr(i, j))) {
  
                if (dp[i] == -1) {
                    continue;
                }
                if (dp[i + j] == -1) {
                    dp[i + j] = dp[i] + 1;
                }
                else {
  
                    // Minimum of dp[i + j] and
                    // dp[i] + 1 will be stored
                    dp[i + j]
                        = min(dp[i + j], dp[i] + 1);
                }
            }
        }
    }
  
    // Return the answer
    return dp[str1.size()];
}
  
// Driver Code
int main()
{
    string str = "GEEKSFORGEEKS",
           wrd = "SFORGEEK";
  
    // Print the string
    cout << partCount(str, wrd);
}
Output
3

Time Complexity: O(N^3), where N is length of str1
Auxiliary Space: O(N^2)




My Personal Notes arrow_drop_up
Recommended Articles
Page :