Longest Palindromic Substring
Longest Palindromic Substring
In the longest palindromic substring problem we have to find the length of longest substring of the given string which is a palindrome. It is a famous interview question asked in many coding interviews as well as coding rounds. In this article, we will be explanation solution with c++ code.
Longest Palindromic Substring Problem Description
In this problem we are given a input string consisting of english alphabets. We have to return the length a longest palindromic substring possible. A substring is a string that is formed by removing any number of characters (including 0) from the input string from front or back.
Input:
- Single line input containing an input string.
Output:
- Longest length required.
Longest Palindromic Substring Solution
The problem is similar to longest palindromic substring with little changes.
Algorithm
- Create a dp table (boolean type) where if dp[i][j] is true this implies substring[i…j] is a palindrome.
- The dp transitions will be –
if(s[i] == s[j] && substring s[i+1…j-1] is palindrome)
dp[i][j] = true (ie it also palindrome)
- We will fill base case ie mark all 1 character length substrings in dp table as palindrome.
- We will iterate for all possible lengths of substrings and use above formulae.
Time & Space Complexity – O(N*N), where N = length of input string.
Code
Output
kabcdcbaqxaba
7
Explanation - abcdcba is the longest palindromic substring.
Login/Signup to comment