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
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Return a Palindromic String after removing minimum length Prefix from given String
Next article icon

Print the longest palindromic prefix of a given string

Last Updated : 07 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string str, the task is to find the longest palindromic prefix of the given string.

Examples: 

Input: str = "abaac" 
Output: aba 
Explanation: 
The longest prefix of the given string which is palindromic is "aba".

Input: str = "abacabaxyz" 
Output: abacaba 
Explanation: 
The prefixes of the given string which is palindromic are "aba" and "abacabaxyz". 
But the longest of among two is "abacabaxyz". 
 

Naive Approach: The idea is to generate all the substring of the given string from the starting index and check whether the substrings are palindromic or not. The palindromic string with a maximum length is the resultant string.

Below is the implementation of the above approach: 

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the longest prefix // which is palindromic void LongestPalindromicPrefix(string s) {      // Find the length of the given string     int n = s.length();      // For storing the length of longest     // prefix palindrome     int max_len = 0;      // Loop to check the substring of all     // length from 1 to N which is palindrome     for (int len = 1; len <= n; len++) {          // String of length i         string temp = s.substr(0, len);          // To store the reversed of temp         string temp2 = temp;          // Reversing string temp2         reverse(temp2.begin(), temp2.end());          // If string temp is palindromic         // then update the length         if (temp == temp2) {             max_len = len;         }     }      // Print the palindromic string of     // max_len     cout << s.substr(0, max_len); }  // Driver Code int main() {      // Given string     string str = "abaab";      // Function Call     LongestPalindromicPrefix(str); } 
Java
// Java program for the above approach import java.util.*; class GFG{  // Function to find the longest prefix // which is palindromic static void LongestPalindromicPrefix(String s) {      // Find the length of the given String     int n = s.length();      // For storing the length of longest     // prefix palindrome     int max_len = 0;      // Loop to check the subString of all     // length from 1 to N which is palindrome     for (int len = 1; len <= n; len++)     {          // String of length i         String temp = s.substring(0, len);          // To store the reversed of temp         String temp2 = temp;          // Reversing String temp2         temp2 = reverse(temp2);          // If String temp is palindromic         // then update the length         if (temp.equals(temp2))         {             max_len = len;         }     }      // Print the palindromic String of     // max_len     System.out.print(s.substring(0, max_len)); }  static String reverse(String input)  {     char[] a = input.toCharArray();     int l, r = a.length - 1;     for (l = 0; l < r; l++, r--)      {         char temp = a[l];         a[l] = a[r];         a[r] = temp;     }     return String.valueOf(a); }   // Driver Code public static void main(String[] args) {      // Given String     String str = "abaab";      // Function Call     LongestPalindromicPrefix(str); } }  // This code is contributed by Rajput-Ji 
Python3
# Python3 program for the above approach   # Function to find the longest prefix # which is palindrome def LongestPalindromicPrefix(string):          # Find the length of the given string     n = len(string)          # For storing the length of longest      # Prefix Palindrome     max_len = 0          # Loop to check the substring of all      # length from 1 to n which is palindrome     for length in range(0, n + 1):                  # String of length i         temp = string[0:length]                  # To store the value of temp         temp2 = temp                  # Reversing the value of temp          temp3 = temp2[::-1]                  # If string temp is palindromic          # then update the length         if temp == temp3:             max_len = length          # Print the palindromic string      # of max_len     print(string[0:max_len])  # Driver code if __name__ == '__main__' :          string = "abaac";          # Function call     LongestPalindromicPrefix(string)      # This code is contributed by virusbuddah_ 
C#
// C# program for the above approach using System;  class GFG{  // Function to find the longest prefix // which is palindromic static void longestPalindromicPrefix(String s) {      // Find the length of the given String     int n = s.Length;      // For storing the length of longest     // prefix palindrome     int max_len = 0;      // Loop to check the subString of all     // length from 1 to N which is palindrome     for (int len = 1; len <= n; len++)     {          // String of length i         String temp = s.Substring(0, len);          // To store the reversed of temp         String temp2 = temp;          // Reversing String temp2         temp2 = reverse(temp2);          // If String temp is palindromic         // then update the length         if (temp.Equals(temp2))         {             max_len = len;         }     }      // Print the palindromic String of     // max_len     Console.Write(s.Substring(0, max_len)); }  static String reverse(String input)  {     char[] a = input.ToCharArray();     int l, r = a.Length - 1;     for (l = 0; l < r; l++, r--)      {         char temp = a[l];         a[l] = a[r];         a[r] = temp;     }     return String.Join("",a); }   // Driver Code public static void Main(String[] args) {      // Given String     String str = "abaab";      // Function Call     longestPalindromicPrefix(str); } }  // This code is contributed by amal kumar choubey 
JavaScript
<script>      // JavaScript program for the above approach          // Function to find the longest prefix     // which is palindromic     function LongestPalindromicPrefix(s)     {          // Find the length of the given String         let n = s.length;          // For storing the length of longest         // prefix palindrome         let max_len = 0;          // Loop to check the subString of all         // length from 1 to N which is palindrome         for (let len = 1; len <= n; len++)         {              // String of length i             let temp = s.substring(0, len);              // To store the reversed of temp             let temp2 = temp;              // Reversing String temp2             temp2 = reverse(temp2);              // If String temp is palindromic             // then update the length             if (temp == temp2)             {                 max_len = len;             }         }          // Print the palindromic String of         // max_len         document.write(s.substring(0, max_len));     }      function reverse(input)     {         let a = input.split('');         let l, r = a.length - 1;         for (l = 0; l < r; l++, r--)         {             let temp = a[l];             a[l] = a[r];             a[r] = temp;         }         return a.join("");     }          // Given String     let str = "abaab";       // Function Call     LongestPalindromicPrefix(str);  </script> 

Output: 
aba

 

Time Complexity: O(N2), where N is the length of the given string.

Efficient Approach: The idea is to use preprocessing algorithm KMP Algorithm. Below are the steps: 

  • Create a temporary string(say str2) which is:
str2 = str + '?' reverse(str);
  • Create an array(say lps[]) of size of length of the string str2 which will store the longest palindromic prefix which is also a suffix of string str2.
  • Update the lps[] by using preprocessing algorithm of KMP Search Algorithm.
  • lps[length(str2) - 1] will give the length of the longest palindromic prefix string of the given string str.

Below is the implementation of the above approach: 

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the longest prefix // which is palindromic void LongestPalindromicPrefix(string str) {      // Create temporary string     string temp = str + '?';      // Reverse the string str     reverse(str.begin(), str.end());      // Append string str to temp     temp += str;      // Find the length of string temp     int n = temp.length();      // lps[] array for string temp     int lps[n];      // Initialise every value with zero     fill(lps, lps + n, 0);      // Iterate the string temp     for (int i = 1; i < n; i++) {          // Length of longest prefix         // till less than i         int len = lps[i - 1];          // Calculate length for i+1         while (len > 0                && temp[len] != temp[i]) {             len = lps[len - 1];         }          // If character at current index         // len are same then increment         // length by 1         if (temp[i] == temp[len]) {             len++;         }          // Update the length at current         // index to len         lps[i] = len;     }      // Print the palindromic string of     // max_len     cout << temp.substr(0, lps[n - 1]); }  // Driver's Code int main() {      // Given string     string str = "abaab";      // Function Call     LongestPalindromicPrefix(str); } 
Java
// Java program for the above approach import java.util.*;  class GFG{  // Function to find the longest  // prefix which is palindromic static void LongestPalindromicPrefix(String str) {      // Create temporary String     String temp = str + '?';      // Reverse the String str     str = reverse(str);      // Append String str to temp     temp += str;      // Find the length of String temp     int n = temp.length();      // lps[] array for String temp     int []lps = new int[n];      // Initialise every value with zero     Arrays.fill(lps, 0);      // Iterate the String temp     for(int i = 1; i < n; i++)     {                 // Length of longest prefix        // till less than i        int len = lps[i - 1];                // Calculate length for i+1        while (len > 0 && temp.charAt(len) !=                           temp.charAt(i))         {            len = lps[len - 1];        }                // If character at current index        // len are same then increment        // length by 1        if (temp.charAt(i) == temp.charAt(len))        {            len++;        }                // Update the length at current        // index to len        lps[i] = len;     }      // Print the palindromic String      // of max_len     System.out.print(temp.substring(0, lps[n - 1])); }  static String reverse(String input) {     char[] a = input.toCharArray();     int l, r = a.length - 1;          for(l = 0; l < r; l++, r--)     {        char temp = a[l];        a[l] = a[r];        a[r] = temp;     }     return String.valueOf(a); }  // Driver Code public static void main(String[] args) {      // Given String     String str = "abaab";      // Function Call     LongestPalindromicPrefix(str); } }  // This code is contributed by Rajput-Ji 
Python3
# Python3 program for the above approach   # Function to find the longest prefix  # which is palindromic  def LongestPalindromicPrefix(Str):      # Create temporary string     temp = Str + "?"      # Reverse the string Str     Str = Str[::-1]      # Append string Str to temp     temp = temp + Str      # Find the length of string temp     n = len(temp)      # lps[] array for string temp     lps = [0] * n      # Iterate the string temp     for i in range(1, n):          # Length of longest prefix          # till less than i         Len = lps[i - 1]          # Calculate length for i+1         while (Len > 0 and temp[Len] != temp[i]):             Len = lps[Len - 1]          # If character at current index         # Len are same then increment         # length by 1         if (temp[i] == temp[Len]):             Len += 1          # Update the length at current         # index to Len         lps[i] = Len      # Print the palindromic string     # of max_len     print(temp[0 : lps[n - 1]])  # Driver Code if __name__ == '__main__':          # Given string     Str = "abaab"      # Function call     LongestPalindromicPrefix(Str)  # This code is contributed by himanshu77 
C#
// C# program for the above approach using System;  class GFG{  // Function to find the longest  // prefix which is palindromic static void longestPalindromicPrefix(String str) {          // Create temporary String     String temp = str + '?';      // Reverse the String str     str = reverse(str);      // Append String str to temp     temp += str;      // Find the length of String temp     int n = temp.Length;      // lps[] array for String temp     int []lps = new int[n];      // Iterate the String temp     for(int i = 1; i < n; i++)     {                // Length of longest prefix        // till less than i        int len = lps[i - 1];                // Calculate length for i+1        while (len > 0 && temp[len] != temp[i])         {            len = lps[len - 1];        }                // If character at current index        // len are same then increment        // length by 1        if (temp[i] == temp[len])        {            len++;        }                // Update the length at current        // index to len        lps[i] = len;     }          // Print the palindromic String      // of max_len     Console.Write(temp.Substring(0, lps[n - 1])); }  static String reverse(String input) {     char[] a = input.ToCharArray();     int l, r = a.Length - 1;          for(l = 0; l < r; l++, r--)     {        char temp = a[l];        a[l] = a[r];        a[r] = temp;     }     return String.Join("", a); }  // Driver Code public static void Main(String[] args) {      // Given String     String str = "abaab";      // Function Call     longestPalindromicPrefix(str); } }  // This code is contributed by Rajput-Ji 
JavaScript
<script>  // Javascript program for the above approach  // Function to find the longest  // prefix which is palindromic function longestPalindromicPrefix(str) {          // Create temporary String     let temp = str + '?';      // Reverse the String str     str = reverse(str);      // Append String str to temp     temp += str;      // Find the length of String temp     let n = temp.length;      // lps[] array for String temp     let lps = new Array(n);     lps.fill(0);      // Iterate the String temp     for(let i = 1; i < n; i++)     {                  // Length of longest prefix         // till less than i         let len = lps[i - 1];                  // Calculate length for i+1         while (len > 0 && temp[len] != temp[i])          {             len = lps[len - 1];         }                  // If character at current index         // len are same then increment         // length by 1         if (temp[i] == temp[len])         {             len++;         }                  // Update the length at current         // index to len         lps[i] = len;     }      // Print the palindromic String      // of max_len     document.write(temp.substring(0, lps[n - 1])); }  function reverse(input) {     let a = input.split('');     let l, r = a.length - 1;      for(l = 0; l < r; l++, r--)     {         let temp = a[l];         a[l] = a[r];         a[r] = temp;     }     return a.join(""); }  // Driver code  // Given String let str = "abaab";  // Function Call longestPalindromicPrefix(str);  // This code is contributed by mukesh07  </script> 

Output: 
aba

 

Time Complexity: O(N), where N is the length of the given string. 
Auxiliary Space: O(N), where N is the length of the given string.
 


Next Article
Return a Palindromic String after removing minimum length Prefix from given String

C

code181
Improve
Article Tags :
  • Misc
  • Strings
  • DSA
  • palindrome
  • prefix
Practice Tags :
  • Misc
  • palindrome
  • Strings

Similar Reads

  • Length of longest palindromic sub-string : Recursion
    Given a string S, the task is to find the length of the longest sub-string which is a palindromeExamples: Input: S = "aaaabbaa" Output: 6 Explanation: Sub-string "aabbaa" is the longest palindromic sub-string. Input: S = "banana" Output: 5 Explanation: Sub-string "anana" is the longest palindromic s
    6 min read
  • Print longest palindrome word in a sentence
    Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other t
    14 min read
  • Longest palindromic string possible after removal of a substring
    Given a string str, the task is to find the longest palindromic string that can be obtained from it after removing a substring. Examples: Input: str = "abcdefghiedcba" Output: "abcdeiedcba" Explanation: Removal of substring "fgh" leaves the remaining string palindromic Input: str = "abba" Output: "a
    11 min read
  • Return a Palindromic String after removing minimum length Prefix from given String
    Given a string B, the task is to find the minimum length prefix of the string which, when removed and added to the end of the string, will make the string a palindrome. Return the palindromic string. If no such string exists, we need to determine that. Examples: Input: "aabb"Output: "abba"Explanatio
    5 min read
  • Length of Longest Palindrome Substring
    Given a string S of length N, the task is to find the length of the longest palindromic substring from a given string. Examples: Input: S = "abcbab"Output: 5Explanation: string "abcba" is the longest substring that is a palindrome which is of length 5. Input: S = "abcdaa"Output: 2Explanation: string
    15+ min read
  • Longest palindromic string formed by concatenation of prefix and suffix of a string
    Given string str, the task is to find the longest palindromic substring formed by the concatenation of the prefix and suffix of the given string str. Examples: Input: str = "rombobinnimor" Output: rominnimor Explanation: The concatenation of string "rombob"(prefix) and "mor"(suffix) is "rombobmor" w
    11 min read
  • Rearrange string to obtain Longest Palindromic Substring
    Given string str, the task is to rearrange the given string to obtain the longest palindromic substring. Examples: Input: str = “geeksforgeeks”Output: eegksfskgeeorExplanation: eegksfskgee is the longest palindromic substring after rearranging the string.Therefore, the required output is eegksfskgee
    9 min read
  • Print all palindrome permutations of a string
    Given a string s, consisting of lowercase Latin characters [a-z]. Find out all the possible palindromes that can be generated using the letters of the string and print them in lexicographical order. Note: Return an empty array if no possible palindromic string can be formed. Examples: Input: s = aab
    10 min read
  • Longest Palindromic Substring using Dynamic Programming
    Given a string s, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first occurrence of the longest palindromic substring from left to right. Examples: Input: s = "aaaabbaa"Output: "aabbaa"Explanation: The longest palindromic substring is
    7 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
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