Algorithms Interview Questions Python

Finding the Longest Palindromic Subsequence

Introduction:

Dynamic Programming (DP) is a powerful algorithmic technique used to solve a variety of optimization problems. One classic problem where DP shines is in finding the longest palindromic subsequence in a given string. In this tutorial, we’ll delve into the intricacies of this problem and learn how to tackle it using DP.

Problem Statement:

You have been given a string ‘A’ consisting of lowercase English letters. Your task is to find the length of the longest palindromic subsequence in ‘A’. Remember, a subsequence is a sequence generated from a string after deleting some or no characters of the string without changing the order of the remaining string characters.

Input Format:
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow. The only line of each test case contains a single string ‘A’ consisting of only lowercase English letters.Code language: JavaScript (javascript)
Output Format:
For each test case, print a single integer denoting the length of the longest palindromic subsequence in string ‘A’. The output for each test case is in a separate line.Code language: PHP (php)
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.Code language: PHP (php)
Constraints:
1 <= T <= 10 1 <= N <= 10 ^ 2 Where ‘T’ is the number of test cases, and ‘N’ is the length of the string. Time limit: 1 sec.

Understanding the Approach: To solve this problem efficiently, we’ll utilize a dynamic programming approach. We’ll create a 2D table where dp[i][j] represents the length of the longest palindromic subsequence in the substring A[i:j+1].

Algorithm:

  1. Initialize a 2D table, dp, to store the lengths of longest palindromic subsequences.
  2. Base case: Set dp[i][i] = 1 for every character i (each character is a palindrome of length 1).
  3. Iterate over the lengths of substrings from 2 to n (n is the length of the string).
  4. For each length l, iterate over the starting index i of the substring.
  5. Calculate the ending index j = i + l – 1.
  6. If A[i] == A[j], set dp[i][j] = dp[i+1][j-1] + 2, as we can extend the palindromic subsequence by including the characters at positions i and j.
  7. If A[i] != A[j], set dp[i][j] = max(dp[i+1][j], dp[i][j-1]), as we need to find the maximum length of palindromic subsequence by excluding either character at positions i or j.
  8. The length of the longest palindromic subsequence in the whole string is at dp[0][n-1].

Implementation in Python:

def longest_palindromic_subsequence(A):
    n = len(A)
    dp = [[0] * n for _ in range(n)]
    
    for i in range(n):
        dp[i][i] = 1
    
    for l in range(2, n+1):
        for i in range(n-l+1):
            j = i + l - 1
            if A[i] == A[j]:
                dp[i][j] = dp[i+1][j-1] + 2
            else:
                dp[i][j] = max(dp[i+1][j], dp[i][j-1])
    
    return dp[0][n-1]

# Example usage:
A = "abcbd"
print(longest_palindromic_subsequence(A))  # Output should be 5 for "abdba"
Code language: Python (python)

Conclusion: Dynamic Programming provides an efficient solution to find the longest palindromic subsequence in a given string. By understanding the problem and implementing the DP approach, you can tackle similar optimization problems effectively. Keep practicing and exploring the power of DP in solving various computational challenges.

Leave a Reply

Discover more from Geeky Codes

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from Geeky Codes

Subscribe now to keep reading and get access to the full archive.

Continue reading