Print the longest prefix of the given string which is also the suffix of the same string

Given a string str, the task is to find the longest prefix which is also the suffix of the given string. The prefix and suffix should not overlap. If no such prefix exists then print -1.

Examples:

Input: str = “aabcdaabc”
Output: aabc
The string “aabc” is the longest
prefix which is also suffix.



Input: str = “aaaa”
Output: aa

Approach: The idea is to use pre-processing algorithm of KMP search. In this algorithm, we build lps array which stores the following values:

lps[i] = the longest proper prefix of pat[0..i]
which is also a suffix of pat[0..i].

We get the length using the above approach, then print the same number of characters from the front which is our answer.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Returns length of the longest prefix
// which is also suffix and the two do
// not overlap. This function mainly is
// copy of computeLPSArray() in KMP Algorithm
int LengthlongestPrefixSuffix(string s)
{
    int n = s.length();
  
    int lps[n];
  
    // lps[0] is always 0
    lps[0] = 0;
  
    // Length of the previous
    // longest prefix suffix
    int len = 0;
  
    // Loop to calculate lps[i]
    // for i = 1 to n - 1
    int i = 1;
    while (i < n) {
        if (s[i] == s[len]) {
            len++;
            lps[i] = len;
            i++;
        }
        else {
  
            // This is tricky. Consider
            // the example. AAACAAAA
            // and i = 7. The idea is
            // similar to search step.
            if (len != 0) {
                len = lps[len - 1];
  
                // Also, note that we do
                // not increment i here
            }
  
            // If len = 0
            else {
                lps[i] = 0;
                i++;
            }
        }
    }
  
    int res = lps[n - 1];
  
    // Since we are looking for
    // non overlapping parts
    return (res > n / 2) ? n / 2 : res;
}
  
// Function that returns the prefix
string longestPrefixSuffix(string s)
{
    // Get the length of the longest prefix
    int len = LengthlongestPrefixSuffix(s);
  
    // Stores the prefix
    string prefix = "";
  
    // Traverse and add charcaters
    for (int i = 0; i < len; i++)
        prefix += s[i];
  
    // Returns the prefix
    return prefix;
}
  
// Driver code
int main()
{
    string s = "abcab";
    string ans = longestPrefixSuffix(s);
    if (ans == "")
        cout << "-1";
    else
        cout << ans;
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach 
class GfG 
  
// Returns length of the longest prefix 
// which is also suffix and the two do 
// not overlap. This function mainly is 
// copy of computeLPSArray() in KMP Algorithm 
static int LengthlongestPrefixSuffix(String s) 
    int n = s.length(); 
  
    int lps[] = new int[n]; 
  
    // lps[0] is always 0 
    lps[0] = 0
  
    // Length of the previous 
    // longest prefix suffix 
    int len = 0
  
    // Loop to calculate lps[i] 
    // for i = 1 to n - 1 
    int i = 1
    while (i < n) 
    
        if (s.charAt(i) == s.charAt(len)) 
        
            len++; 
            lps[i] = len; 
            i++; 
        
        else 
        
  
            // This is tricky. Consider 
            // the example. AAACAAAA 
            // and i = 7. The idea is 
            // similar to search step. 
            if (len != 0
            
                len = lps[len - 1]; 
  
                // Also, note that we do 
                // not increment i here 
            
  
            // If len = 0 
            else 
            
                lps[i] = 0
                i++; 
            
        
    
  
    int res = lps[n - 1]; 
  
    // Since we are looking for 
    // non overlapping parts 
    return (res > n / 2) ? n / 2 : res; 
  
// Function that returns the prefix 
static String longestPrefixSuffix(String s) 
    // Get the length of the longest prefix 
    int len = LengthlongestPrefixSuffix(s); 
  
    // Stores the prefix 
    String prefix = ""
  
    // Traverse and add charcaters 
    for (int i = 0; i < len; i++) 
        prefix += s.charAt(i); 
  
    // Returns the prefix 
    return prefix; 
  
// Driver code 
public static void main(String[] args) 
    String s = "abcab"
    String ans = longestPrefixSuffix(s); 
    if (ans == ""
        System.out.println("-1"); 
    else
        System.out.println(ans); 
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation of the approach
  
# Returns length of the longest prefix
# which is also suffix and the two do
# not overlap. This function mainly is
# copy of computeLPSArray() in KMP Algorithm
def LengthlongestPrefixSuffix(s):
    n = len(s)
  
    lps = [0 for i in range(n)]
  
    # Length of the previous
    # longest prefix suffix
    len1 = 0
  
    # Loop to calculate lps[i]
    # for i = 1 to n - 1
    i = 1
    while (i < n):
        if (s[i] == s[len1]):
            len1 += 1
            lps[i] = len1
            i += 1
          
        else:
              
            # This is tricky. Consider
            # the example. AAACAAAA
            # and i = 7. The idea is
            # similar to search step.
            if (len1 != 0):
                len1 = lps[len1 - 1]
  
                # Also, note that we do
                # not increment i here
              
            # If len = 0
            else:
                lps[i] = 0
                i += 1
  
    res = lps[n - 1]
      
    # Since we are looking for
    # non overlapping parts
    if (res > int(n / 2)):
        return int(n / 2)
    else:
        return res
  
# Function that returns the prefix
def longestPrefixSuffix(s):
      
    # Get the length of the longest prefix
    len1 = LengthlongestPrefixSuffix(s)
  
    # Stores the prefix
    prefix = ""
  
    # Traverse and add charcaters
    for i in range(len1):
        prefix += s[i]
  
    # Returns the prefix
    return prefix
  
# Driver code
if __name__ == '__main__':
    s = "abcab"
    ans = longestPrefixSuffix(s)
    if (ans == ""):
        print("-1")
    else:
        print(ans)
          
# This code is contributed by
# Surendra_Gangwar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach 
using System;
  
class GfG 
  
    // Returns length of the longest prefix 
    // which is also suffix and the two do 
    // not overlap. This function mainly is 
    // copy of computeLPSArray() in KMP Algorithm 
    static int LengthlongestPrefixSuffix(string s) 
    
        int n = s.Length; 
      
        int []lps = new int[n]; 
      
        // lps[0] is always 0 
        lps[0] = 0; 
      
        // Length of the previous 
        // longest prefix suffix 
        int len = 0; 
      
        // Loop to calculate lps[i] 
        // for i = 1 to n - 1 
        int i = 1; 
        while (i < n) 
        
            if (s[i] == s[len]) 
            
                len++; 
                lps[i] = len; 
                i++; 
            
            else
            
      
                // This is tricky. Consider 
                // the example. AAACAAAA 
                // and i = 7. The idea is 
                // similar to search step. 
                if (len != 0) 
                
                    len = lps[len - 1]; 
      
                    // Also, note that we do 
                    // not increment i here 
                
      
                // If len = 0 
                else
                
                    lps[i] = 0; 
                    i++; 
                
            
        
      
        int res = lps[n - 1]; 
      
        // Since we are looking for 
        // non overlapping parts 
        return (res > n / 2) ? n / 2 : res; 
    
      
    // Function that returns the prefix 
    static String longestPrefixSuffix(string s) 
    
        // Get the length of the longest prefix 
        int len = LengthlongestPrefixSuffix(s); 
      
        // Stores the prefix 
        string prefix = ""
      
        // Traverse and add charcaters 
        for (int i = 0; i < len; i++) 
            prefix += s[i]; 
      
        // Returns the prefix 
        return prefix; 
    
      
    // Driver code 
    public static void Main() 
    
        string s = "abcab"
        string ans = longestPrefixSuffix(s); 
        if (ans == ""
            Console.WriteLine("-1"); 
        else
            Console.WriteLine(ans); 
    }
  
// This code is contributed by Ryuga

chevron_right


Output:

ab


My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.