The Wayback Machine - https://web.archive.org/web/20240717181827/https://www.geeksforgeeks.org/length-of-longest-palindromic-sub-string-recursion/
Open In App

Length of longest palindromic sub-string : Recursion

Last Updated : 09 Jan, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Given a string S, the task is to find the length longest sub-string which is a palindrome
Examples: 

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 sub-string. 
 

Approach:The idea is to use recursion to break the problem into smaller sub-problems. In order to break the problem into two smaller sub-problems, Compare the start and end characters of the string and recursively call the function for the middle substring. Below is the illustration of the recursion: 
 

  • Base Case: The base case for this problem is when the starting index of the string is greater than or equal to the ending index. 
if (start > end)
    return count
if (start == end)
    return count + 1
  • Recursive Case: Compare the characters at the start and end index of the string: 
    • When starting and ending characters are equal, then recursively call for the substring by excluding the starting and ending characters 
recursive_func(string, start+1, end-1)
  • When starting and ending characters are not equal, then recursively call for the substring by excluding the starting and ending characters one at a time. 
recursive_func(string, start+1, end)
recursive_func(string, start, end-1)
  • Return statement: At each recursive call, return the maximum count possible by including and excluding the start and end characters. 

Below is the implementation of above approach: 

C++




// C++ implementation to find the
// length of longest palindromic
// sub-string using Recursion
 
#include <iostream>
using namespace std;
 
// Function to find maximum
// of the two variables
int max(int x, int y)
{
    return (x > y) ? x : y;
}
 
// Function to find the longest
// palindromic substring : Recursion
int longestPalindromic(string str,
             int i, int j, int count)
{
     
    // Base condition when the start
    // index is greater than end index
    if (i > j)
        return count;
     
    // Base condition when both the
    // start and end index are equal
    if (i == j)
        return (count + 1);
         
    // Condition when corner characters
    // are equal in the string
    if (str[i] == str[j]) {
         
        // Recursive call to find the
        // longest Palindromic string
        // by excluding the corner characters
        count = longestPalindromic(str, i + 1,
                  j - 1, count + 2);
        return max(count,
        max(longestPalindromic(str, i + 1, j, 0),
         longestPalindromic(str, i, j - 1, 0)));
    }
     
    // Recursive call to find the
    // longest Palindromic string
    // by including one corner
    // character at a time
    return max(
       longestPalindromic(str, i + 1, j, 0),
       longestPalindromic(str, i, j - 1, 0));
}
 
// Function to find the longest
// palindromic sub-string
int longest_palindromic_substr(string str)
{
    // Utility function call
    return longestPalindromic(str, 0,
                 str.length() - 1, 0);
}
 
// Driver Code
int main()
{
    string str = "aaaabbaa";
     
    // Function Call
    cout << longest_palindromic_substr(str);
    return 0;
}


Java




// Java implementation to find the
// length of longest palindromic
// sub-String using Recursion
class GFG{
  
// Function to find maximum
// of the two variables
static int max(int x, int y)
{
    return (x > y) ? x : y;
}
  
// Function to find the longest
// palindromic subString : Recursion
static int longestPalindromic(String str,
             int i, int j, int count)
{
      
    // Base condition when the start
    // index is greater than end index
    if (i > j)
        return count;
      
    // Base condition when both the
    // start and end index are equal
    if (i == j)
        return (count + 1);
          
    // Condition when corner characters
    // are equal in the String
    if (str.charAt(i) == str.charAt(j)) {
          
        // Recursive call to find the
        // longest Palindromic String
        // by excluding the corner characters
        count = longestPalindromic(str, i + 1,
                  j - 1, count + 2);
        return max(count,
        max(longestPalindromic(str, i + 1, j, 0),
         longestPalindromic(str, i, j - 1, 0)));
    }
      
    // Recursive call to find the
    // longest Palindromic String
    // by including one corner
    // character at a time
    return Math.max(
       longestPalindromic(str, i + 1, j, 0),
       longestPalindromic(str, i, j - 1, 0));
}
  
// Function to find the longest
// palindromic sub-String
static int longest_palindromic_substr(String str)
{
    // Utility function call
    return longestPalindromic(str, 0,
                 str.length() - 1, 0);
}
  
// Driver Code
public static void main(String[] args)
{
    String str = "aaaabbaa";
      
    // Function Call
    System.out.print(longest_palindromic_substr(str));
}
}
 
// This code is contributed by Rajput-Ji


Python3




# Python3 implementation to find the
# length of longest palindromic
# sub-string using Recursion
 
# Function to find maximum
# of the two variables
def maxi(x, y) :
    if x > y :
        return x
    else :
        return y
 
# Function to find the longest
# palindromic substring : Recursion
def longestPalindromic(strn, i, j, count):
     
    # Base condition when the start
    # index is greater than end index
    if i > j :
        return count
     
    # Base condition when both the
    # start and end index are equal
    if i == j :
        return (count + 1)
         
    # Condition when corner characters
    # are equal in the string
    if strn[i] == strn[j] :
         
        # Recursive call to find the
        # longest Palindromic string
        # by excluding the corner characters
        count = longestPalindromic(strn, i + 1, j - 1, count + 2)
        return maxi(count, maxi(longestPalindromic(strn, i + 1, j, 0),
                    longestPalindromic(strn, i, j - 1, 0)))
     
    # Recursive call to find the
    # longest Palindromic string
    # by including one corner
    # character at a time
    return maxi( longestPalindromic(strn, i + 1, j, 0),
                longestPalindromic(strn, i, j - 1, 0))
 
# Function to find the longest
# palindromic sub-string
def longest_palindromic_substr(strn):
 
    # Utility function call
    k = len(strn) - 1
    return longestPalindromic(strn, 0, k, 0)
 
strn = "aaaabbaa"
 
# Function Call
print( longest_palindromic_substr(strn) )
     
# This code is contributed by chsadik99   
    


C#




// C# implementation to find the
// length of longest palindromic
// sub-String using Recursion
using System;
 
class GFG{
   
// Function to find maximum
// of the two variables
static int max(int x, int y)
{
    return (x > y) ? x : y;
}
   
// Function to find the longest
// palindromic subString : Recursion
static int longestPalindromic(String str,
             int i, int j, int count)
{
       
    // Base condition when the start
    // index is greater than end index
    if (i > j)
        return count;
       
    // Base condition when both the
    // start and end index are equal
    if (i == j)
        return (count + 1);
           
    // Condition when corner characters
    // are equal in the String
    if (str[i] == str[j]) {
           
        // Recursive call to find the
        // longest Palindromic String
        // by excluding the corner characters
        count = longestPalindromic(str, i + 1,
                  j - 1, count + 2);
        return max(count,
        max(longestPalindromic(str, i + 1, j, 0),
         longestPalindromic(str, i, j - 1, 0)));
    }
       
    // Recursive call to find the
    // longest Palindromic String
    // by including one corner
    // character at a time
    return Math.Max(
       longestPalindromic(str, i + 1, j, 0),
       longestPalindromic(str, i, j - 1, 0));
}
   
// Function to find the longest
// palindromic sub-String
static int longest_palindromic_substr(String str)
{
    // Utility function call
    return longestPalindromic(str, 0,
                 str.Length - 1, 0);
}
   
// Driver Code
public static void Main(String[] args)
{
    String str = "aaaabbaa";
       
    // Function Call
    Console.Write(longest_palindromic_substr(str));
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
    // Javascript implementation to find the
    // length of longest palindromic
    // sub-String using Recursion
     
    // Function to find maximum
    // of the two variables
    function max(x, y)
    {
        return (x > y) ? x : y;
    }
 
    // Function to find the longest
    // palindromic subString : Recursion
    function longestPalindromic(str, i, j, count)
    {
 
        // Base condition when the start
        // index is greater than end index
        if (i > j)
            return count;
 
        // Base condition when both the
        // start and end index are equal
        if (i == j)
            return (count + 1);
 
        // Condition when corner characters
        // are equal in the String
        if (str[i] == str[j]) {
 
            // Recursive call to find the
            // longest Palindromic String
            // by excluding the corner characters
            count = longestPalindromic(str, i + 1,
                      j - 1, count + 2);
            return max(count,
            max(longestPalindromic(str, i + 1, j, 0),
             longestPalindromic(str, i, j - 1, 0)));
        }
 
        // Recursive call to find the
        // longest Palindromic String
        // by including one corner
        // character at a time
        return Math.max(
           longestPalindromic(str, i + 1, j, 0),
           longestPalindromic(str, i, j - 1, 0));
    }
 
    // Function to find the longest
    // palindromic sub-String
    function longest_palindromic_substr(str)
    {
        // Utility function call
        return longestPalindromic(str, 0, str.length - 1, 0);
    }
     
    let str = "aaaabbaa";
         
    // Function Call
    document.write(longest_palindromic_substr(str));
 
// This code is contributed by mukesh07.
</script>


Output: 

6

 

Time Complexity : The time complexity of this code is O(n^2) as there are two recursive calls in each iteration and the loop iterates over all characters of the string.

Auxiliary Space : The space complexity is O(n) as the recursive function calls consume space on the call stack.



Previous Article
Next Article

Similar Reads

Generate an N-length string having longest palindromic substring of length K
Given two integers N and K (K ? N), the task is to obtain a string of length N such that maximum length of a palindromic substring of this string is K. Examples: Input: N = 5, K = 3 Output: "abacd" Explanation: Palindromic substrings are "a", "b", "c", "d" and "aba". Therefore, the longest palindromic substring from the given string is of length 3.
4 min read
Check if a string contains a palindromic sub-string of even length
S is string containing only lowercase English alphabets. We need to find if there exists at least one palindromic sub-string whose length is even. Examples: Input : aassssOutput : YESInput : gfgOutput : NOApproach: Approach to solve this problem is to check all even-length substrings of the given string and check if any of them is a palindrome. Thi
8 min read
Lexicographically smallest permutation of a string that can be reduced to length K by removing K-length prefixes from palindromic substrings of length 2K
Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible". Examples: Input: str = "0000100001100001”, K = 4O
14 min read
Longest Palindromic Substring using Palindromic Tree | Set 3
Given a string, find the longest substring which is a palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”. Prerequisite : Palindromic Tree | Longest Palindromic Substring Structure of Palindromic Tree : The palindromic Tree’s actual structure is close to the directed graph. It is actually a merged s
15+ min read
Length of longest Palindromic Subsequence of even length with no two adjacent characters same
Given a string str, the task is to find the length of the longest palindromic subsequence of even length with no two adjacent characters same except the middle characters. Examples: Input: str = "abscrcdba" Output: 6 Explanation: abccba is the required string which has no two consecutive characters same except the middle characters. Hence the lengt
11 min read
Number of strings of length N with no palindromic sub string
Given two positive integers N, M. The task is to find the number of strings of length N under the alphabet set of size M such that no substrings of size greater than 1 is palindromic. Examples: Input : N = 2, M = 3 Output : 6 In this case, set of alphabet are 3, say {A, B, C} All possible string of length 2, using 3 letters are: {AA, AB, AC, BA, BB
5 min read
Count the number of sub-arrays such that the average of elements present in the sub-array is greater than that not present in the sub-array
Given an array of integers arr[], the task is to count the number of sub-arrays such that the average of elements present in the sub-array is greater than the average of elements that are not present in the sub-array.Examples: Input: arr[] = {6, 3, 5} Output: 3 The sub-arrays are {6}, {5} and {6, 3, 5} because their averages are greater than {3, 5}
8 min read
Minimum cuts required to convert a palindromic string to a different palindromic string
Given palindromic string s, the task is to find minimum k, such that you can cut this string into k+1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. If it is impossible then print -1.Examples: Input : string = "civic" Output : 2 Explanation : ci | v | ic --&gt; ic |
15+ min read
Find the count of palindromic sub-string of a string in its sorted form
Given string str consisting of lowercase English alphabets, the task is to find the total number of palindromic sub-strings present in the sorted form of str. Examples: Input: str = "acbbd" Output: 6 All palindromic sub-string in it's sorted form ("abbcd") are "a", "b", "b", "bb", "c" and "d". Input: str = "abbabdbd" Output: 16 Naive approach: One
5 min read
Check if all the palindromic sub-strings are of odd length
Given a string 's' check if all of its palindromic sub-strings are of odd length or not. If yes then print "YES" or "NO" otherwise. Examples: Input: str = "geeksforgeeks" Output: NO Since, "ee" is a palindromic sub-string of even length. Input: str = "madamimadam" Output: YES Brute Force Approach: Simply, iterate over each sub-string of ‘s’ and che
10 min read
three90RightbarBannerImg