Solution: Longest Palindromic Subsequence
This review provides a detailed analysis of the different ways to solve the longest palindromic subsequence problem.
Solution #1: Brute force
First, let’s start by looking at the brute force solution to solve this problem.
Explanation
In this brute force solution:
-
If the element at the beginning and the end are the same, we increment the count by two and make a recursive call for the remaining sequence (lines 13-14).
-
Otherwise, we skip the element either from the beginning or the end to make two recursive calls for the remaining subsequence (lines 17-18).
-
After that, we return the greater result (line 19).
Time complexity
The time complexity of the above algorithm is exponential , where n is the length of the input sequence. The space complexity is which is the maximum number of times that the function is called. So, this is the space used to store the recursion stack.
Solution #2: Memoization
The brute force recursive solution results in redundant recursive calls. We can try and memoize the code to reduce the number of same recursive calls.
Let’s take a look at how this can be ...