Welcome back.
So this is the approach that we have discussed already in detail when we were discussing the palindromic
substrings question.
So this is the tabulation approach.
So again remember we had this table over here and we iterated lengthwise.
And we either filled true or false in these cells.
So that's how we solved that question.
Now let's make use of this and try to solve the longest palindromic substring.
So how we are going to solve this is we'll have a variable.
Let's just call it longest.
And initially, let's say longest is just an empty string.
Now what we will do is as we go through these diagonals, or as we iterate through these cells in a
length wise manner, whenever we get true, we will fill that particular substring to longest.
Okay.
So let's see how that pans out.
So initially for example, when we are over here we get true and we will set longest to P okay.
Because it's starting at zero and going up to index zero.
And this will keep happening.
And when we come over here longest would be s because again we have true over here.
And we will change whatever we had previously in longest to the new value that we're getting over here,
or to the new string for which we have identified that that particular substring is a palindrome.
So at the end of this iteration, longest will be the substring s.
Okay.
Now when we go through these cells over here we see that everything is false.
So longest does not change.
And then when we come to this part over here to the third iteration, we get true over here.
And at this point longest would be changed to p q p okay.
And then we get again true over here, at which point longest would be changed to p r p.
Notice that whenever we are getting true, we will be getting a substring which will either have the
same length as the string which is already stored in longest or a greater length.
And the reason for this is because we are iterating length wise.
Okay, so the length over here is one.
The length over here is two, the length over here is three.
And it goes on in this manner okay.
So again over here for this example because we have false in all of these cells, the answer finally
will be p r p.
And that is what we will finally just return.
So this is how we can solve this question.
Notice that it's pretty straightforward.
It's just a minor tweak to the solution that we had come up with for the palindromic substring question.