Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
Length of all prefixes that are also the suffixes of given string
Next article icon

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

Last Updated : 01 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given 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 the pre-processing algorithm of the 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++




// 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 characters
    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;
}
 
 

Java




// 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 characters
    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);
}
}
 
 

Python3




# 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 characters
    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
 
 

C#




// 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 characters
        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
 
 

Javascript




<script>
 
// JavaScript 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
function LengthlongestPrefixSuffix(s)
{
    var n = s.length;
 
    var lps = Array.from({length: n}, (_, i) => 0);
 
    // lps[0] is always 0
    lps[0] = 0;
 
    // Length of the previous
    // longest prefix suffix
    var len = 0;
 
    // Loop to calculate lps[i]
    // for i = 1 to n - 1
    var 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++;
            }
        }
    }
 
    var res = lps[n - 1];
 
    // Since we are looking for
    // non overlapping parts
    return (res > n / 2) ? n / 2 : res;
}
 
// Function that returns the prefix
function longestPrefixSuffix(s)
{
    // Get the length of the longest prefix
    var len = LengthlongestPrefixSuffix(s);
 
    // Stores the prefix
    var prefix = "";
 
    // Traverse and add characters
    for (var i = 0; i < len; i++)
        prefix += s.charAt(i);
 
    // Returns the prefix
    return prefix;
}
 
// Driver code
var s = "abcab";
var ans = longestPrefixSuffix(s);
if (ans == "")
    document.write("-1");
else
    document.write(ans);
 
// This code contributed by shikhasingrajput
 
</script>
 
 
Output
ab

Time Complexity: O(N), as we are using a loop to traverse N times to build los array. Where N is the length of the string.
Auxiliary Space: O(N), as we are using extra space for the lps array. Where N is the length of the string.



Next Article
Length of all prefixes that are also the suffixes of given string

S

Striver
Improve
Article Tags :
  • DSA
  • Pattern Searching
  • Strings
  • prefix
Practice Tags :
  • Pattern Searching
  • Strings

Similar Reads

  • Find the longest sub-string which is prefix, suffix and also present inside the string | Set 2
    Given string str. The task is to find the longest sub-string which is a prefix, a suffix and a sub-string of the given string, str. If no such string exists then print -1.Examples: Input: str = "geeksisforgeeksinplatformgeeks" Output: geeksInput: str = “fixprefixsuffix” Output: fix Note: The Set-1 o
    9 min read
  • Find the longest sub-string which is prefix, suffix and also present inside the string
    Given string str. The task is to find the longest sub-string which is a prefix, a suffix, and a sub-string of the given string, str. If no such string exists then print -1.Examples: Input: str = "fixprefixsuffix" Output: fix "fix" is a prefix, suffix and present inside in the string too.Input: str =
    10 min read
  • Find the Longest Non-Prefix-Suffix Substring in the Given String
    Given a string s of length n. The task is to determine the longest substring t such that t is neither the prefix nor the suffix of string s, and that substring must appear as both prefix and suffix of the string s. If no such string exists, print -1. Example: Input: s = "fixprefixsuffix"Output: fix
    7 min read
  • Length of all prefixes that are also the suffixes of given string
    Given a string S consisting of N characters, the task is to find the length of all prefixes of the given string S that are also suffixes of the same string S. Examples: Input: S = "ababababab"Output: 2 4 6 8Explanation: The prefixes of S that are also its suffixes are: "ab" of length = 2"abab" of le
    10 min read
  • Longest string which is prefix string of at least two strings
    Given a set of strings of the same length, we need to find the length of the longest string, which is a prefix string of at least two strings. Examples: Input: ["abcde", "abcsd", "bcsdf", "abcda", "abced"] Output: 4 Explanation: Longest prefix string is "abcd". Input: ["pqrstq", "pwxyza", "abcdef",
    6 min read
  • Remove longest prefix of the String which has duplicate substring
    Given a string S of length N, the task is to remove the longest prefix of the string which has at least one duplicate substring present in S. Note: The duplicate substring cannot be the prefix itself Examples: Input: S = "GeeksforGeeks"Output: "forGeeks"Explanation: The longest substring which has a
    5 min read
  • Longest string in an array which matches with prefix of the given string
    Given an array of strings arr[] and Q queries where each query consists of a string str, the task is to find the longest string in the array that matches with prefix of the given string str i.e. the string must be prefix of str. Examples: Input: arr[] = {"GeeksForGeeks", "GeeksForGeeksd", "Arnab", "
    8 min read
  • Longest sub string of 0's in a binary string which is repeated K times
    Given binary string S of size N and a number K. The task is to find the Longest sub string of 0's in the string which is formed by repeating given string K times. Examples: Input : S = "100001" , K = 3 Output : 4 After repeating given string 3 time, string becomes 100001100001100001. The longest sub
    5 min read
  • Find length of longest subsequence of one string which is substring of another string
    Given two strings X and Y. The task is to find the length of the longest subsequence of string X which is a substring in sequence Y. Examples: Input : X = "ABCD", Y = "BACDBDCD"Output : 3Explanation: "ACD" is longest subsequence of X which is substring of Y. Input : X = "A", Y = "A"Output : 1 Perqui
    15+ min read
  • Sub-strings of a string that are prefix of the same string
    Given a string str, the task is to count all possible sub-strings of the given string that are prefix of the same string. Examples: Input: str = "ababc" Output: 7 All possible sub-string are "a", "ab", "aba", "abab", "ababc", "a" and "ab" Input: str = "abdabc" Output: 8 Approach: Traverse the string
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences