Given a string, find the maximum length contiguous substring of it that is also a palindrome. For example, the longest palindromic substring of “bananas” is “anana”, and the longest palindromic substring of “abdcbcdbdcbbc” is “bdcbcdb”.

The problem differs from the problem of finding the longest palindromic subsequence. Unlike subsequences, substrings are required to occupy consecutive positions within the original string.

Note that the longest palindromic substring is not guaranteed to be unique. For example, there is no palindromic substring in a string abracadabra with a length greater than three. Still, there are two palindromic substrings with length three, namely, aca and ada. If multiple longest palindromic substring exists, return any one of them.

Practice this problem

 
The dynamic programming solution for this problem takes O(n2) time and O(n2) space. This post will discuss another approach to solve this problem that doesn’t require any extra space.

The idea is simple and effective – for each character in the given string, consider it the midpoint of a palindrome and expand in both directions to find the maximum length palindrome. For an even length palindrome, consider every adjacent pair of characters as the midpoint.

 
Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The longest palindromic substring of ABDCBCDBDCBBC is BDCBCDB

Java


Download  Run Code

Output:

The longest palindromic substring of ABDCBCDBDCBBC is BDCBCDB

Python


Download  Run Code

Output:

The longest palindromic substring of ABDCBCDBDCBBC is BDCBCDB

The time complexity of the above solution is O(n2) and requires O(n) extra space, where n is the length of the input string. Note that O(n) solution is also possible for this problem by using Manacher’s algorithm.