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 Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimum length of substring whose rotation generates a palindromic substring
Next article icon

Maximum length palindromic substring such that it starts and ends with given char

Last Updated : 08 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string str and a character ch, the task is to find the longest palindromic sub-string of str such that it starts and ends with the given character ch.
Examples: 
 

Input: str = “lapqooqpqpl”, ch = ‘p’ 
Output: 6 
“pqooqp” is the maximum length palindromic 
sub-string that starts and ends with ‘p’.
Input: str = “geeksforgeeks”, ch = ‘k’ 
Output: 1 
“k” is the valid sub-string. 
 

 

Approach: For every possible index pair (i, j) such that str[i] = str[j] = ch check whether the sub-string str[i…j] is palindrome or not. For all the found palindromes, store the length of the longest palindrome found so far.
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that returns true if
// str[i...j] is a palindrome
bool isPalindrome(string str, int i, int j)
{
    while (i < j) {
        if (str[i] != str[j])
            return false;
        i++;
        j--;
    }
    return true;
}
 
// Function to return the length of the
// longest palindromic sub-string such that
// it starts and ends with the character ch
int maxLenPalindrome(string str, int n, char ch)
{
    int maxLen = 0;
 
    for (int i = 0; i < n; i++) {
 
        // If current character is
        // a valid starting index
        if (str[i] == ch) {
 
            // Instead of finding the ending index from
            // the beginning, find the index from the end
            // This is because if the current sub-string
            // is a palindrome then there is no need to check
            // the sub-strings of smaller length and we can
            // skip to the next iteration of the outer loop
            for (int j = n - 1; j >= i; j--) {
 
                // If current character is
                // a valid ending index
                if (str[j] == ch) {
 
                    // If str[i...j] is a palindrome then update
                    // the length of the maximum palindrome so far
                    if (isPalindrome(str, i, j)) {
                        maxLen = max(maxLen, j - i + 1);
                        break;
                    }
                }
            }
        }
    }
    return maxLen;
}
 
// Driver code
int main()
{
    string str = "lapqooqpqpl";
    int n = str.length();
    char ch = 'p';
 
    cout << maxLenPalindrome(str, n, ch);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
class GFG
{
     
    // Function that returns true if
    // str[i...j] is a palindrome
    static boolean isPalindrome(String str,
                               int i, int j)
    {
        while (i < j)
        {
            if (str.charAt(i) != str.charAt(j))
            {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
 
    // Function to return the length of the
    // longest palindromic sub-string such that
    // it starts and ends with the character ch
    static int maxLenPalindrome(String str, int n, char ch)
    {
        int maxLen = 0;
 
        for (int i = 0; i < n; i++)
        {
 
            // If current character is
            // a valid starting index
            if (str.charAt(i) == ch)
            {
 
                // Instead of finding the ending index from
                // the beginning, find the index from the end
                // This is because if the current sub-string
                // is a palindrome then there is no need to check
                // the sub-strings of smaller length and we can
                // skip to the next iteration of the outer loop
                for (int j = n - 1; j >= i; j--)
                {
 
                    // If current character is
                    // a valid ending index
                    if (str.charAt(j) == ch)
                    {
 
                        // If str[i...j] is a palindrome then update
                        // the length of the maximum palindrome so far
                        if (isPalindrome(str, i, j))
                        {
                            maxLen = Math.max(maxLen, j - i + 1);
                            break;
                        }
                    }
                }
            }
        }
        return maxLen;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str = "lapqooqpqpl";
        int n = str.length();
        char ch = 'p';
 
        System.out.println(maxLenPalindrome(str, n, ch));
    }
}
 
// This code is contributed by Princi Singh
 
 

Python3




# Python implementation of the approach
 
# Function that returns true if
# str[i...j] is a palindrome
def isPalindrome(str, i, j):
    while (i < j):
        if (str[i] != str[j]):
            return False;
        i+=1;
        j-=1;
    return True;
 
 
# Function to return the length of the
# longest palindromic sub-string such that
# it starts and ends with the character ch
def maxLenPalindrome(str, n, ch):
    maxLen = 0;
 
    for i in range(n):
 
        # If current character is
        # a valid starting index
        if (str[i] == ch):
 
            # Instead of finding the ending index from
            # the beginning, find the index from the end
            # This is because if the current sub-string
            # is a palindrome then there is no need to check
            # the sub-strings of smaller length and we can
            # skip to the next iteration of the outer loop
            for j in range(n-1,i+1,-1):
                # If current character is
                # a valid ending index
                if (str[j] == ch):
 
                    # If str[i...j] is a palindrome then update
                    # the length of the maximum palindrome so far
                    if (isPalindrome(str, i, j)):
                        maxLen = max(maxLen, j - i + 1);
                        break;
 
    return maxLen;
 
# Driver code
str = "lapqooqpqpl";
n = len(str);
ch = 'p';
 
print(maxLenPalindrome(str, n, ch));
     
# This code is contributed by 29AjayKumar
 
 

C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function that returns true if
    // str[i...j] is a palindrome
    static bool isPalindrome(string str,
                            int i, int j)
    {
        while (i < j)
        {
            if (str[i] != str[j])
            {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
 
    // Function to return the length of the
    // longest palindromic sub-string such that
    // it starts and ends with the character ch
    static int maxLenPalindrome(string str, int n, char ch)
    {
        int maxLen = 0;
 
        for (int i = 0; i < n; i++)
        {
 
            // If current character is
            // a valid starting index
            if (str[i] == ch)
            {
 
                // Instead of finding the ending index from
                // the beginning, find the index from the end
                // This is because if the current sub-string
                // is a palindrome then there is no need to check
                // the sub-strings of smaller length and we can
                // skip to the next iteration of the outer loop
                for (int j = n - 1; j >= i; j--)
                {
 
                    // If current character is
                    // a valid ending index
                    if (str[j] == ch)
                    {
 
                        // If str[i...j] is a palindrome then update
                        // the length of the maximum palindrome so far
                        if (isPalindrome(str, i, j))
                        {
                            maxLen = Math.Max(maxLen, j - i + 1);
                            break;
                        }
                    }
                }
            }
        }
        return maxLen;
    }
 
    // Driver code
    public static void Main()
    {
        string str = "lapqooqpqpl";
        int n = str.Length;
        char ch = 'p';
 
        Console.WriteLine(maxLenPalindrome(str, n, ch));
    }
}
 
// This code is contributed by AnkitRai01
 
 

Javascript




<script>
      // JavaScript implementation of the approach
      // Function that returns true if
      // str[i...j] is a palindrome
      function isPalindrome(str, i, j) {
        while (i < j) {
          if (str[i] !== str[j]) {
            return false;
          }
          i++;
          j--;
        }
        return true;
      }
 
      // Function to return the length of the
      // longest palindromic sub-string such that
      // it starts and ends with the character ch
      function maxLenPalindrome(str, n, ch) {
        var maxLen = 0;
 
        for (var i = 0; i < n; i++) {
          // If current character is
          // a valid starting index
          if (str[i] === ch) {
            // Instead of finding the ending index from
            // the beginning, find the index from the end
            // This is because if the current sub-string
            // is a palindrome then there is no need to check
            // the sub-strings of smaller length and we can
            // skip to the next iteration of the outer loop
            for (var j = n - 1; j >= i; j--) {
              // If current character is
              // a valid ending index
              if (str[j] === ch) {
                // If str[i...j] is a palindrome then update
                // the length of the maximum palindrome so far
                if (isPalindrome(str, i, j)) {
                  maxLen = Math.max(maxLen, j - i + 1);
                  break;
                }
              }
            }
          }
        }
        return maxLen;
      }
 
      // Driver code
      var str = "lapqooqpqpl";
      var n = str.length;
      var ch = "p";
 
      document.write(maxLenPalindrome(str, n, ch));
    </script>
 
 
Output: 
6

 

Time Complexity: O(n3) Space Complexity: O(1)


Next Article
Minimum length of substring whose rotation generates a palindromic substring
author
prajmsidc
Improve
Article Tags :
  • Arrays
  • DSA
  • Searching
  • Strings
  • palindrome
  • substring
Practice Tags :
  • Arrays
  • palindrome
  • Searching
  • Strings

Similar Reads

  • Maximum length palindromic substring for every index such that it starts and ends at that index
    Given a string S, the task for every index of the string is to find the length of the longest palindromic substring that either starts or ends at that index. Examples: Input: S = "bababa"Output: 5 5 3 3 5 5Explanation:Longest palindromic substring starting at index 0 is "babab". Therefore, length =
    15+ min read
  • Maximum even length sub-string that is permutation of a palindrome
    Given string [Tex]str [/Tex], the task is to find the maximum length of the sub-string of [Tex]str [/Tex]that can be arranged into a Palindrome (i.e at least one of its permutation is a Palindrome). Note that the sub-string must be of even length. Examples: Input: str = "124565463" Output: 6 "456546
    9 min read
  • Minimum replacements such that no palindromic substring of length exceeding 1 is present in the given string
    Given a string str consisting of lowercase characters, the task is to modify the string such that it does not contain any palindromic substring of length exceeding 1 by minimum replacement of characters. Examples: Input: str = �"Output: 4String can be modified to "bacbacb" by replacing 4 characters.
    9 min read
  • Maximum length palindrome that can be created with characters in range L and R
    Given a string str and Q queries. Each query consists of two numbers L and R. The task is to find the maximum length palindrome that can be created with characters in the range [L, R]. Examples: Input: str = "amim", Q[] = {{1, 4}, {3, 4} Output: 3 1 In range [1, 4], only two palindromes "mam" and "m
    10 min read
  • Minimum length of substring whose rotation generates a palindromic substring
    Given a string str, the task is to find the minimum length of substring required to rotate that generates a palindromic substring from the given string. Examples: Input: str = "abcbd" Output: 0 Explanation: No palindromic substring can be generated. There is no repeated character in the string. Inpu
    7 min read
  • Maximize the minimum length of K palindromic Strings formed from given String
    Given a string str of length N, and an integer K, the task is to form K different strings by choosing characters from the given string such that all the strings formed are palindrome and the length of the smallest string among the K strings is maximum possible. Examples: Input: str = "qrsprtps", K =
    10 min read
  • Count maximum-length palindromes in a String
    Given a string, count how many maximum-length palindromes are present. (It need not be a substring) Examples: Input : str = "ababa" Output: 2 Explanation : palindromes of maximum of lengths are : "ababa", "baaab" Input : str = "ababab" Output: 4 Explanation : palindromes of maximum of lengths are :
    9 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 st
    8 min read
  • Binary String of given length that without a palindrome of size 3
    Given an integer n. Find a string of characters 'a' and 'b' such that the string doesn't contain any palindrome of length 3. Examples: Input : 3 Output : "aab" Explanation: aab is not a palindrome. Input : 5 Output : aabba Explanation: aabba does not contain a palindrome of size 3. The approach here
    3 min read
  • Split a String into two Substring such that the sum of unique characters is maximum
    Given a string str, the task is to partition the string into two substrings such that the sum of unique characters of both substrings is the maximum possible. Examples: Input: str = "abcabcd” Output: 7Explanation: Partition the given string into "abc" and "abcd", the sum of unique characters is 3 +
    14 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