Longest Palindromic Subsequence (LPS)

beginner
11 min

Longest Palindromic Subsequence (LPS)

Welcome to this in-depth guide on the Longest Palindromic Subsequence (LPS)! šŸŽ‰

In this lesson, we'll explore the Longest Palindromic Subsequence problem, a classic algorithm problem that asks for the longest palindromic sequence within a given string. This problem is crucial for understanding dynamic programming and string manipulation.

What is a Palindrome? šŸ’”

A palindrome is a sequence that reads the same backward as forward. For example: "racecar", "madam", "level".

The Longest Palindromic Subsequence Problem šŸ“

Given a string, find the longest palindromic subsequence (not necessarily a palindrome itself). For instance, the longest palindromic subsequence for the string "banana" is "anana".

How to Solve the LPS Problem šŸŽÆ

The LPS problem can be solved using dynamic programming. We create an n x n matrix, where dp[i][j] represents the length of the longest palindromic subsequence ending at i and j.

Dynamic Programming Approach šŸ“

  1. Initialize the matrix with all elements as 0.
  2. Iterate from i=0 to n-1 for the first row, and from j=0 to n-1 for the first column.
  3. For the rest of the matrix, calculate each cell using the following formula:
python
if (s[i] == s[j]): dp[i][j] = 1 + dp[i+1][j-1] else: dp[i][j] = max(dp[i][j-1], dp[i+1][j])
  1. The maximum element in the last row is the length of the longest palindromic subsequence.

Code Examples šŸ’»

Here's a Python example for the LPS problem:

python
def longest_palindromic_subsequence(s): n = len(s) dp = [[0]*n for _ in range(n)] for i in range(n): dp[i][i] = 1 for end in range(2, n+1): for i in range(n-end+1): j = i + end - 1 if s[i] == s[j]: dp[i][j] = dp[i+1][j-1] + 2 else: dp[i][j] = max(dp[i][j-1], dp[i+1][j]) return dp[0][-1]
Quick Quiz
Question 1 of 1

What is the time complexity of the Longest Palindromic Subsequence solution?

Let's dive deeper into the LPS problem, explore its applications, and even try to optimize the solution. Happy coding! šŸš€