Finding the Longest Palindrome in a String
Hey ! Finding the longest palindrome in a string is one of the most commonly asked interview questions if you're aspiring to be a software development engineer. In this post we will be dealing with an optimal solution for this problem. There are two ways to solve the problem. They are listed down as follows.
- Initialise result to an empty string.
- Loop through each character of the string.
- Find for a matching character.
- See if the string bounded by the two characters form a palindrome. If they do then check if the length of this string is greater than the string in result variable. If else assign the string to result.
This is an obvious solution for the problem but this is a brute force approach and is the least efficient of all the approaches. The main pitfall being the repeated checking of palindromic strings. To overcome this we can go for a dynamic approach which is discussed below.
This is based on the concept that if the string asasa has to be a palindrome then the string sas must be a palindrome. In this approach we maintain a boolean table of size n x n, where n is the length of the string. If the cell (i, j) of the table has a value 1 then the string bound by the indices i and j (i.e. s[i]....s[j]) is a palindrome and vice versa. The algorithm is as follows
- Initialise a boolean table of size n x n to 0, where n is the length of the string.
- Check for the following two basis steps.
- Change the values of the leading diagonal to 1 as a single character always forms a palindrome.
- Loop through the string and check if the string bound by i and i+1 forms a palindrome and if it does change the value of (i, i+1) in the table to 1.
- We have now checked for a single character and two characters. Now run a loop (i loop) from 3 to n-1.
- Run an inner loop (j loop) which would loop through the characters of the given string.
- To check if the string bound by j and j+i is a palindrome we have to check if s[j] and s[j+i] are equal (as a palindrome always starts and ends with the same character) and if table[j][j+i-1] is 1 (as the inner string must be a palindrome for the current string to be a palindrome).
- Change the value of table[j][j+i] to 1 if the conditions are satisfied.
- If the string is a palindrome then update the result variable to the current string.
Feel free to post your solution to the problem in the comments section below. Happy Coding :)