Mark As Completed Discussion

One Pager Cheat Sheet

  • Find the length of the longest palindromic subsequence of a given string s, consisting of only lowercase English letters and with length no greater than 1000.
  • A brute-force approach to checking for the longest palindromic subsequence could be to directly check for palindromic subsequences and find the one with the longest length.
  • The brute force approach to finding the length of the longest palindromic subsequence involves checking all possible subsequences of the given string, and is not ideal due to its exponential time complexity.
  • We can reduce the time complexity of our problem by utilizing the bottom-up dynamic programming approach, which uses a 2D grid to store the result of each subproblem and reference it in constant time.
  • Dynamic programming is a technique used to solve problems through breaking them down into smaller subproblems that exhibit optimal substructure and overlapping subproblems, allowing us to solve them using a bottom-up tabulation approach to store the results of each subproblem.
  • We fill a 4 x 4 grid by traversing the given string s "cbbd" with two pointers, one working in reverse and the other traversing normally, to store the length of the longest palindromic subsequence encountered so far.
  • Fill the grid[i][j] with 1 for diagonals that represent one element, as the length of the palindromic subsequence for one character is 1.
  • All elements below the diagonal of the table should be set to 0 as they represent invalid subsequences due to their start point being after their end point.
  • We traverse the grid bottom-up to find the length of the Longest Palindromic Subsequence which is returned by the top-right element of the matrix.
  • The time complexity of the solution is O(n<sup>2</sup>), as it takes n2 time to create, traverse and fill the 2D grid of size n x n.
  • The problem can be solved using the memoization approach of dynamic programming, reducing the time complexity to O(n<sup>2</sup>).

This is our final solution.

To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Great job getting through this. Let's move on.

If you had any problems with this tutorial, check out the main forum thread here.