


A substring is a contiguous sequence of elements within a string (for example, “bcd” is a substring of “abcde” while “bce” is not).
A string is said to be palindrome if the reverse of the string is the same as the actual string. For example, “abba” is a palindrome, but “abbc” is not a palindrome.
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.
The only line of each test case contains a single string ‘S’ consisting of only lowercase English letters.
For each test case, print a single string in a single line denoting the longest palindromic substring of string ‘S’.
The output for each test case is in a separate line.
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= N <= 100
Where ‘N’ is the length of the string.
Time limit: 1 sec
The brute force solution is to pick all possible starting and ending positions for a substring and verify if it is a palindrome.
The steps are as follows:
To improve our brute force solution, we first observe how we can avoid unnecessary re-computation while we are validating if a substring is a palindrome or not. Consider the case "xyzyx". Assume if we already know that "yzy" is a palindrome, then it seems obvious that "xyzyx" must be a palindrome since the two left and right end letters are the same.
The time complexity can be reduced by storing the prior results of its subproblems.
The steps are as follows:
When you observe closely you will realise that a palindrome has mirrors around its centre, a palindrome can be expanded in both directions from its centre.
The steps are as follows:
For example, in a string “abbab” of length 5, there are 5 possibilities that a palindrome can originate from the 5 indexes, so there are 5 substrings: “a”, “b”, “b”, “bab”, and “b” respectively (These are the longest palindromic substrings possible originating from each index of the string). All these accounts for an odd length palindrome.
Now, what about even length palindromes? Since there are 4 spaces in between the 5 characters of the given string, so the longest palindromic substrings possible originating from each space of the given string are “”, “abba”, “”, and “” respectively.
Now out of all these 9 possibilities, the longest palindromic substring is “abba”.
We keep on expanding the palindrome considering these centres as the centre of each substring, and simultaneously we keep on validating if the substring originating from each centre is a palindrome or not.