Now let's operate on all remaining substrings. How will we check if the substring is a palindrome? We will compare the element in the starting position and element in the ending position, and move "in-wards", saving a lot of effort by eliminating unnecessary work.
1for start = end, "a" is palindromic,
2for start + 1 = end, "aa" is palindromic (if string[start] = string[end])
3for start + 2 = end, "aba" is palindromic (if string[start] = string[end] and "b" is palindromic)
4for start + 3 = end, "abba" is palindromic (if string[start] = string[end] and "bb" is palindromic)
The big idea is that we won't have to repeatedly check substrings that can't possibly be a palindrome. If both elements are the same, our substring is a palindrome, and we continue the check by moving towards the middle with two pointers. Otherwise, if it's not a palindrome, our "starting point" already verifies that.
But we'll need to build up this table to know. For traversing the table above the diagonal, we can use the following code:
So, the above loops will traverse the area above the diagonal in a bottom-up manner (for example, (3, 4)
, (2, 3)
, (2, 4)
.. and so on). Then we'll see if the substring is a palindrome or not. At the first iteration, the loop will check the (3, 4)
substring (i.e start is 3 and the end is 4).
In this case, there will be no value at (3, 4)
because the substring is not a palindrome. We will keep checking the substrings and get the longest palindromic substring at the end.