Given a string S of length **N **and integer K, find the smallest length string which contains the string **S **as a sub string exactly K times.

Examples:

Input:_ S = “abba”, K = 3_

_Output: _abbabbabba

Explanation:_ The string “abba” occurs K times in the string abbabbabba, i.e. {abbabbabba, abbabbabba, abbabbabba}_

Input:_ S = “geeksforgeeks”, K = 3_

Output:_ “geeksforgeeksforgeeksforgeeks”_

Approach: To optimize the above approach, find the Longest Proper Prefix which is also a suffix for the given string S, and then generate a substring of S excluding the longest common prefix and add this substring to the answer exactly K – 1 times to the original string. Follow the below steps to solve the problem:

• Find the length of the longest proper prefix using KMP algorithm.
• Append substring **S.substring(N-lps[N-1]) **to S, exactly K-1 times.
• Below is the implementation of the above approach.

### C++

• `// C++ Program to implement`

• `// the above approach`

• `#include <bits/stdc++.h>`

• `**using**` `**namespace**` `std;`

• `// KMP algorithm`

• `**int**``* kmp(string& s)`

• `{`

• `**int**` `n = s.size();`

• `**int**``* lps =` `**new**` `**int**``[n];`

• `lps[0] = 0;`

• `**int**` `i = 1, len = 0;`

• `**while**` `(i < n) {`

• `**if**` `(s[i] == s[len]) {`

• `len++;`

• `lps[i] = len;`

• `i++;`

• `}`

• `**else**` `{`

• `**if**` `(len != 0) {`

• `len = lps[len - 1];`

• `}`

• `**else**` `{`

• `lps[i] = 0;`

• `i++;`

• `}`

• `}`

• `}`

• `**return**` `lps;`

• `}`

• `// Function to return the required string`

• `string findString(string& s,` `**int**` `k)`

• `{`

• `**int**` `n = s.length();`

• `// Finding the longest proper prefix`

• `// which is also suffix`

• `**int**``* lps = kmp(s);`

• `// ans string`

• `string ans =` `""``;`

• `string suff`

• `= s.substr(0, n - lps[n - 1]);`

• `**for**` `(``**int**` `i = 0; i < k - 1; ++i) {`

• `// Update ans appending the`

• `// substring K - 1 times`

• `ans += suff;`

• `}`

• `// Append the original string`

• `ans += s;`

• `// Returning min length string`

• `// which contain exactly k`

• `// substring of given string`

• `**return**` `ans;`

• `}`

• `// Driver Code`

• `**int**` `main()`

• `{`

• `**int**` `k = 3;`

• `string s =` `"geeksforgeeks"``;`

• `cout << findString(s, k) << endl;`

• `}`

• Output:

``````geeksforgeeksforgeeksforgeeks
``````
• Time Complexity:_ O(N*K )_
• Auxiliary Space:_ O(K* N)_
• 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.

#dynamic programming #mathematical #pattern searching #searching #strings #prefix #substring #suffix

9.60 GEEK