The Wayback Machine - https://web.archive.org/web/20241217204258/https://www.geeksforgeeks.org/longest-prefix-also-suffix/
Open In App

Longest prefix which is also suffix

Last Updated : 09 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a string s, the task is to find the length of the longest proper prefix which is also a suffix. A proper prefix is a prefix that doesn’t include whole string. For example, prefixes of “abc” are “”, “a”, “ab” and “abc” but proper prefixes are “”, “a” and “ab” only.

Examples: 

Input: s = “aabcdaabc”
Output: 4
Explanation: The string “aabc” is the longest proper prefix which is also the suffix.

Input: s= “ababab”
Output: 4
Explanation: The string “abab” is the longest proper prefix which is also the suffix.

Input: s = “aaaa”
Output: 3
Explanation: The string “aaa” is the longest proper prefix which is also the suffix.

[Naive approach] By Comparing each Proper Prefix with Suffix – O(n^2) Time and O(1) Space

The simplest approach is to compare each proper prefix with the suffix. The minimum length of proper prefix is zero and maximum length is length – 1. So, we iterate over each length, and check if the proper prefix of that size matches with the suffix of the same size. If they match, we update the result accordingly.

C++
// C++ program to find the length of longest proper prefix
// that is also suffix by comparing each prefix with suffix

#include <iostream>
#include <string>
using namespace std;

int longestPrefixSuffix(string s) {
    int res = 0;
    int n = s.length();
    
    // Iterating over all possible lengths
    for (int len = 1; len < n; len++) {
        
        // Starting index of proper prefix
        int i = 0;
        
        // Starting index of suffix
        int j = s.length() - len;
        
        bool flag = true;
        
        // Comparing proper prefix with suffix of length 'len'
        for (int k = 0; k < len; k++) {
            if (s[i + k] != s[j + k]) {  
                flag = false;
                break;
            }
        }
        
        // If they match, update the result
        if (flag)
            res = len;
    }
    
    return res;
}

int main() {
    string s = "ababab";
    cout << longestPrefixSuffix(s); 
    return 0;
}
C
// C program to find the length of longest proper prefix
// that is also suffix by comparing each prefix with suffix

#include <stdio.h>
#include <string.h>

int longestPrefixSuffix(char s[]) {
    int res = 0;
    int n = strlen(s);
    
    // Iterating over all possible lengths
    for (int len = 1; len < n; len++) {
        
        // Starting index of proper prefix
        int i = 0;
        
        // Starting index of suffix
        int j = n - len;
        
        int flag = 1;
        
        // Comparing proper prefix with suffix of length 'len'
        for (int k = 0; k < len; k++) {
            if (s[i + k] != s[j + k]) {  
                flag = 0;
                break;
            }
        }
        
        // If they match, update the result
        if (flag)
            res = len;
    }
    
    return res;
}

int main() {
    char s[] = "ababab";
    printf("%d", longestPrefixSuffix(s)); 
    return 0;
}
Java
// Java program to find the length of longest proper prefix
// that is also suffix by comparing each prefix with suffix

class GfG {
    static int longestPrefixSuffix(String s) {
        int res = 0;
        int n = s.length();

        // Iterating over all possible lengths
        for (int len = 1; len < n; len++) {

            // Starting index of proper prefix
            int i = 0;

            // Starting index of suffix
            int j = s.length() - len;

            boolean flag = true;

            // Comparing proper prefix with suffix of length 'len'
            for (int k = 0; k < len; k++) {
                if (s.charAt(i + k) != s.charAt(j + k)) {  
                    flag = false;
                    break;
                }
            }

            // If they match, update the result
            if (flag)
                res = len;
        }

        return res;
    }

    public static void main(String[] args) {
        String s = "ababab";
        System.out.println(longestPrefixSuffix(s)); 
    }
}
Python
# Python program to find the length of longest proper prefix
# that is also suffix by comparing each prefix with suffix

def longestPrefixSuffix(s):
    res = 0
    n = len(s)
    
    # Iterating over all possible lengths
    for length in range(1, n):
        
        # Starting index of proper prefix
        i = 0
        
        # Starting index of suffix
        j = n - length
        
        flag = True
        
        # Comparing proper prefix with suffix of length 'len'
        for k in range(length):
            if s[i + k] != s[j + k]:
                flag = False
                break
        
        # If they match, update the result
        if flag:
            res = length
    
    return res

s = "ababab"
print(longestPrefixSuffix(s))
C#
// C# program to find the length of longest proper prefix
// that is also suffix by comparing each prefix with suffix

using System;

class GfG {
    static int longestPrefixSuffix(string s) {
        int res = 0;
        int n = s.Length;

        // Iterating over all possible lengths
        for (int len = 1; len < n; len++) {

            // Starting index of proper prefix
            int i = 0;

            // Starting index of suffix
            int j = s.Length - len;

            bool flag = true;

            // Comparing proper prefix with suffix of length 'len'
            for (int k = 0; k < len; k++) {
                if (s[i + k] != s[j + k]) {  
                    flag = false;
                    break;
                }
            }

            // If they match, update the result
            if (flag)
                res = len;
        }

        return res;
    }

    static void Main() {
        string s = "ababab";
        Console.WriteLine(longestPrefixSuffix(s)); 
    }
}
JavaScript
// JavaScript program to find the length of longest proper prefix
// that is also suffix by comparing each prefix with suffix

function longestPrefixSuffix(s) {
    let res = 0;
    let n = s.length;

    // Iterating over all possible lengths
    for (let len = 1; len < n; len++) {

        // Starting index of proper prefix
        let i = 0;

        // Starting index of suffix
        let j = n - len;

        let flag = true;

        // Comparing proper prefix with suffix of length 'len'
        for (let k = 0; k < len; k++) {
            if (s[i + k] !== s[j + k]) {
                flag = false;
                break;
            }
        }

        // If they match, update the result
        if (flag)
            res = len;
    }

    return res;
}

let s = "ababab";
console.log(longestPrefixSuffix(s));

Output
4

[Expected approach] Using LPS of KMP Algorithm – O(n) Time and O(n) Space

The idea is to use the preprocessing step of KMP Algorithm for pattern searching. In this step, we build a lps array, where each index i stores the length of the longest proper prefix of the substring str[0…i] that is also a suffix of the same substring. So, the last index of the lps array will store the length of longest prefix that is also a suffix for the entire string.
You can refer this article to know more about complete construction of LPS array – KMP algorithm for pattern Searching.

C++
// C++ program to find the length of longest proper prefix
// that is also suffix using lps of KMP Algorithm

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int longestPrefixSuffix(string s) {
    int n = s.length();
    vector<int> lps(n);
    
    // len stores the length of longest prefix which
    // is also a suffix for the previous index
    int len = 0;

    // lps[0] is always 0
    lps[0] = 0;

    int i = 1;
    while (i < s.length()) {

        // If characters match, increment the size of lps
        if (s[i] == s[len]) {
            len++;
            lps[i] = len;
            i++;
        }

        // If there is a mismatch
        else {
            if (len != 0) {

                // Update len to the previous lps value
                // to avoid reduntant comparisons
                len = lps[len - 1];
            }
            else {

                // If no matching prefix found, set lps[i] to 0
                lps[i] = 0;
                i++;
            }
        }
    }
    
    // Last element of lps array will store the length of
    // longest prefix that is also suffix of entire string
    return lps[n - 1];
}

int main() {
    string s = "ababab";
    cout << longestPrefixSuffix(s); 
    return 0;
}
C
// C program to find the length of longest proper prefix
// that is also suffix using lps of KMP Algorithm

#include <stdio.h>
#include <string.h>

int longestPrefixSuffix(char s[]) {
    int n = strlen(s);
    int lps[n];
    
    // len stores the length of longest prefix which
    // is also a suffix for the previous index
    int len = 0;

    // lps[0] is always 0
    lps[0] = 0;

    int i = 1;
    while (i < n) {

        // If characters match, increment the size of lps
        if (s[i] == s[len]) {
            len++;
            lps[i] = len;
            i++;
        }

        // If there is a mismatch
        else {
            if (len != 0) {

                // Update len to the previous lps value
                // to avoid redundant comparisons
                len = lps[len - 1];
            }
            else {

                // If no matching prefix found, set lps[i] to 0
                lps[i] = 0;
                i++;
            }
        }
    }
    
    // Last element of lps array will store the length of
    // longest prefix that is also suffix of entire string
    return lps[n - 1];
}

int main() {
    char s[] = "ababab";
    printf("%d", longestPrefixSuffix(s)); 
    return 0;
}
Java
// Java program to find the length of longest proper prefix
// that is also suffix using lps of KMP Algorithm

class GfG {
    static int longestPrefixSuffix(String s) {
        int n = s.length();
        int[] lps = new int[n];
        
        // len stores the length of longest prefix which
        // is also a suffix for the previous index
        int len = 0;

        // lps[0] is always 0
        lps[0] = 0;

        int i = 1;
        while (i < n) {

            // If characters match, increment the size of lps
            if (s.charAt(i) == s.charAt(len)) {
                len++;
                lps[i] = len;
                i++;
            }

            // If there is a mismatch
            else {
                if (len != 0) {

                    // Update len to the previous lps value
                    // to avoid redundant comparisons
                    len = lps[len - 1];
                }
                else {

                    // If no matching prefix found, set lps[i] to 0
                    lps[i] = 0;
                    i++;
                }
            }
        }
        
        // Last element of lps array will store the length of
        // longest prefix that is also suffix of entire string
        return lps[n - 1];
    }

    public static void main(String[] args) {
        String s = "ababab";
        System.out.println(longestPrefixSuffix(s)); 
    }
}
Python
# Python program to find the length of longest proper prefix
# that is also suffix using lps of KMP Algorithm

def longestPrefixSuffix(s):
    n = len(s)
    lps = [0] * n
    
    # len stores the length of longest prefix which
    # is also a suffix for the previous index
    length = 0

    # lps[0] is always 0
    lps[0] = 0

    i = 1
    while i < n:

        # If characters match, increment the size of lps
        if s[i] == s[length]:
            length += 1
            lps[i] = length
            i += 1
        # If there is a mismatch
        else:
            if length != 0:

                # Update length to the previous lps value
                # to avoid redundant comparisons
                length = lps[length - 1]
            else:
              
                # If no matching prefix found, set lps[i] to 0
                lps[i] = 0
                i += 1
    
    # Last element of lps array will store the length of
    # longest prefix that is also suffix of entire string
    return lps[n - 1]

s = "ababab"
print(longestPrefixSuffix(s))
C#
// C# program to find the length of longest proper prefix
// that is also suffix using lps of KMP Algorithm

using System;

class GfG {
    static int longestPrefixSuffix(string s) {
        int n = s.Length;
        int[] lps = new int[n];
        
        // len stores the length of longest prefix which
        // is also a suffix for the previous index
        int len = 0;

        // lps[0] is always 0
        lps[0] = 0;

        int i = 1;
        while (i < n) {

            // If characters match, increment the size of lps
            if (s[i] == s[len]) {
                len++;
                lps[i] = len;
                i++;
            }

            // If there is a mismatch
            else {
                if (len != 0) {

                    // Update len to the previous lps value
                    // to avoid redundant comparisons
                    len = lps[len - 1];
                }
                else {

                    // If no matching prefix found, set lps[i] to 0
                    lps[i] = 0;
                    i++;
                }
            }
        }

        // Last element of lps array will store the length of
        // longest prefix that is also suffix of entire string
        return lps[n - 1];
    }

    static void Main() {
        string s = "ababab";
        Console.WriteLine(longestPrefixSuffix(s));
    }
}
JavaScript
// JavaScript program to find the length of longest proper prefix
// that is also suffix using lps of KMP Algorithm

function longestPrefixSuffix(s) {
    let n = s.length;
    let lps = new Array(n);
    
    // len stores the length of longest prefix which
    // is also a suffix for the previous index
    let len = 0;

    // lps[0] is always 0
    lps[0] = 0;

    let i = 1;
    while (i < n) {

        // If characters match, increment the size of lps
        if (s[i] === s[len]) {
            len++;
            lps[i] = len;
            i++;
        }

        // If there is a mismatch
        else {
            if (len !== 0) {

                // Update len to the previous lps value
                // to avoid redundant comparisons
                len = lps[len - 1];
            }
            else {

                // If no matching prefix found, set lps[i] to 0
                lps[i] = 0;
                i++;
            }
        }
    }
    
    // Last element of lps array will store the length of
    // longest prefix that is also suffix of entire string
    return lps[n - 1];
}

let s = "ababab";
console.log(longestPrefixSuffix(s));

Output
4




Next Article

Similar Reads

three90RightbarBannerImg