19. Longest Palindromic Subsequence
The problem can be found at the following link: Question Link
My Approach
In order to determine the length of the longest palindromic subsequence within a given string, I used the concept of the longest common subsequence. This involved finding the longest common subsequence between the original string, denoted as A
, and its reverse, denoted as rev
. Let's find that out using recursion and memoization.
The
check
function is a recursive auxiliary function that receives the current indicesi
andj
of the original stringA
and the reversed stringrev
, respectively. It also takes the lengthn
of the string and a 2D vectordp
for memoization as parameters.The base case of the recursion is when either
i
orj
reaches the end of the string. In that case, the function returns 0.If the result for the current indices
i
andj
is already computed and stored indp
, it is directly returned.If the characters at indices
i
andj
are the same, we increment the result by 1 and recursively call the function with the incremented indices.We also recursively call the function with the same
i
but incrementedj
and vice versa, and store the maximum of the three results indp[i][j]
.Finally, the function returns the result stored in
dp[0][0]
, which represents the length of the longest palindromic subsequence.
Time and Auxiliary Space Complexity
Time Complexity: Each recursive call reduces the problem size by 1 until
i
orj
reaches the end of the string. Hence, the time complexity can be considered asO(n^2)
, wheren
is the length of the string.Auxiliary Space Complexity: Since memoization array
dp
, which is of sizen x n
. Therefore, the auxiliary space complexity isO(n^2)
.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the getlost01/gfg-potd repository.
Last updated