Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

LONGEST PALINDROMIC

SUBSEQUENCE
TEST TIME ON MINIMUM STACK

URL:
LONGEST PALINDROMIC SUBSEQUENCE

EXPLANATION

Given a string S, find the common palindromic sequence

Palindromic sequence is a sequence that does not need to be contiguous and


is a palindrome, which is common in itself.

You need to return the length of the longest palindromic subsequence in A.

Unlike substrings, subsequences are not required to occupy consecutive


positions within the original string.
LONGEST PALINDROMIC SUBSEQUENCE

EXAMPLE
Consider S = “ABBDCACB”

The length of the longest palindromic subsequence is 5

The longest palindromic subsequence is BCACB

S = “BEBEEED”

The longest common palindromic subsequence is “EEEE”, which has a length of


4
LONGEST PALINDROMIC SUBSEQUENCE

SOLUTION
The idea is to use recursion to solve this problem. The idea is to compare
the last character of the string X[i…j] with its first character. There are
two possibilities
1. If the string’s last character is the same as the first character,
include the first and last characters in palindrome and recur for the
remaining substring X[i+1, j-1].
2. If the last character of the string is different from the first
character, return the maximum of the two values we get by
1. Removing the last character and recursing for the remaining
substring X[i, j-1].
2. Removing the first character and recursing for the remaining
substring X[i+1, j].
LONGEST PALINDROMIC SUBSEQUENCE

SOLUTION

This yields the following recursive relation to finding the length of the
longest repeated subsequence of a sequence X:
LONGEST PALINDROMIC SUBSEQUENCE

PROGRAM

Sample IO
Input
ABBDCACB

Output
5

Time Complexity
O(2^n), where n is the length of the input string
LONGEST PALINDROMIC SUBSEQUENCE

class Main {
public static int findLongestPalindrome(String X, int i, int j) {
if (i > j) {
return 0;
}

if (i == j) {
return 1;
}

if (X.charAt(i) == X.charAt(j)) {
return findLongestPalindrome(X, i + 1, j - 1) + 2;
}

return Integer.max(findLongestPalindrome(X, i, j - 1),


findLongestPalindrome(X, i + 1, j));
}

public static void main(String[] args) {


String X = "ABBDCACB";
int n = X.length();

System.out.print(findLongestPalindrome(X, 0, n - 1));
}
}
LONGEST PALINDROMIC SUBSEQUENCE

TIME AND SPACE COMPLEXITY

Time complexity: O(n^2) - Quadratic time complexity due to the recursive nature of the

algorithm with overlapping subproblems.

Space complexity: O(n^2) - Quadratic space complexity due to the memoization table storing

intermediate results.
LONGEST PALINDROMIC SUBSEQUENCE

IMPROVEMENT

In the previous attempt, the worst case happens when there is no repeated
character present in X (i.e., LPS length is 1)

Also each recursive call will end up in two recursive calls. This also
requires additional space for the call stack.

However, the LPS problem has an optimal substructure and also exhibits
overlapping subproblems.
LONGEST PALINDROMIC SUBSEQUENCE

IMPROVEMENT

Let’s consider the recursion tree for


a sequence of length 6 having all
distinct characters, say ABCDEF, whose
LPS length is 1.
LONGEST PALINDROMIC SUBSEQUENCE

IMPROVEMENT

As we can see, the same subproblems


(highlighted in the same color) are
getting computed repeatedly. We
know that problems with optimal
substructure and overlapping
subproblems can be solved by
dynamic programming, where
subproblem solutions are memorized
rather than computed and again.1.
LONGEST PALINDROMIC SUBSEQUENCE

PROGRAM

Sample IO
Input
ABBDCACB

Output
5
LONGEST PALINDROMIC SUBSEQUENCE

import java.util.HashMap; findLongestPalindrome(X, i + 1, j, lookup)));


import java.util.Map; }
class Main { }
public static int findLongestPalindrome(String X, return lookup.get(key);
int i, int j, Map<String, Integer> lookup) { }
if (i > j) { public static void main(String[] args) {
return 0; String X = "ABBDCACB";
} int n = X.length();
if (i == j) { Map<String, Integer> lookup = new
return 1; HashMap<>();
} System.out.print(findLongestPalindrome(X, 0,
String key = i + "|" + j; n - 1, lookup));
if (!lookup.containsKey(key)) { }
if (X.charAt(i) == X.charAt(j)) { }
lookup.put(key,
findLongestPalindrome(X, i + 1, j - 1, lookup) + 2);
} else {
lookup.put(key,
Integer.max(findLongestPalindrome(X, i, j - 1,
lookup),
LONGEST PALINDROMIC SUBSEQUENCE

TIME AND SPACE COMPLEXITY

Time complexity: O(n^2) - Due to the recursive nature of the algorithm with memoization,

where `n` is the length of the input string.

Space complexity: O(n^2) - Due to the storage of intermediate results in the memoization

table, where `n` is the length of the input string.


LONGEST PALINDROMIC SUBSEQUENCE

PRINTING THE SUBSEQUENCE

The discussed methods only find the longest palindromic subsequence length
but does not print the longest palindromic subsequence itself

The longest palindromic subsequence problem is a classic variation of the


Longest Common Subsequence (LCS) problem

The idea is to find LCS of the given string with its reverse

Call LCS(X, reverse(X)) and the longest common subsequence will be the
longest palindromic subsequence.
LONGEST PALINDROMIC SUBSEQUENCE

PROGRAM

Sample IO
Input
ABBDCACB

Output
5
BCACB
LONGEST PALINDROMIC SUBSEQUENCE

class Main { if (X.charAt(i - 1) == Y.charAt(j - 1)) {


public static String findLongestPalindrome(String lookup[i][j] = lookup[i - 1][j - 1]
X, String Y, int m, int n, int[][] lookup) { + 1;
if (m == 0 || n == 0) { } else {
return ""; lookup[i][j] = Integer.max(lookup[i
} - 1][j], lookup[i][j - 1]);
if (X.charAt(m - 1) == Y.charAt(n - 1)) { }
return findLongestPalindrome(X, Y, m - 1, n }
- 1, lookup) + X.charAt(m - 1); }
} return lookup[n][n];
if (lookup[m - 1][n] > lookup[m][n - 1]) { }
return findLongestPalindrome(X, Y, m - 1, public static void main(String[] args) {
n, lookup); String X = "ABBDCACB";
} String Y = new
return findLongestPalindrome(X, Y, m, n - 1, StringBuilder(X).reverse().toString();
lookup); int[][] lookup = new int[X.length() + 1]
} [X.length() + 1];
public static int LCSLength(String X, String Y, int System.out.println(LCSLength(X, Y, X.length(),
n, int[][] lookup) { lookup));
for (int i = 1; i <= n; i++) { System.out.println(findLongestPalindrome(X, Y,
for (int j = 1; j <= n; j++) { X.length(), X.length(), lookup));
}
}
LONGEST PALINDROMIC SUBSEQUENCE

TIME AND SPACE COMPLEXITY

Time complexity: O(n^2) - Quadratic time complexity due to the recursive nature of the

algorithm with overlapping subproblems.

Space complexity: O(n^2) - Quadratic space complexity due to the memoization table storing

intermediate results.
INTERVIEW QUESTIONS

1. Explain the concept of the Longest Palindromic Subsequence (LPS).

Answer:The Longest Palindromic Subsequence (LPS) of a sequence is the

length of the longest subsequence that is also a palindrome. A subsequence

is obtained by deleting some characters from the original sequence without

changing the relative order of the remaining characters.


INTERVIEW QUESTIONS

2. Describe an algorithm to find the length of the Longest Palindromic


Subsequence in a given sequence.

Answer:One approach is to use dynamic programming. Initialize a 2D array

to store the lengths of palindromic subsequences for different

subproblems. Iterate through the sequence, filling the array based on

whether characters match or not. The final value in the array represents

the length of the Longest Palindromic Subsequence.


INTERVIEW QUESTIONS

3. Can the Longest Palindromic Subsequence include non-contiguous


characters from the original sequence?

Answer:Yes, the Longest Palindromic Subsequence can include non-contiguous

characters. A subsequence is formed by deleting characters, and the order

of the remaining characters matters, not their contiguous arrangement.


INTERVIEW QUESTIONS

4. How would you extend the algorithm to find the actual Longest
Palindromic Subsequence itself, not just its length?

Answer:In addition to storing the lengths in the 2D array, maintain another array

to backtrack the characters contributing to the palindromic subsequence. This

allows reconstructing the actual subsequence by following the path in reverse

order.
INTERVIEW QUESTIONS

5. Discuss an optimization to the dynamic programming approach for


finding the Longest Palindromic Subsequence.

Answer:An optimization involves using a one-dimensional array instead of a 2D

array since each computation depends only on the previous row's values. This

reduces the space complexity from O(n^2) to O(n), making the algorithm more memory-

efficient.
/ethnuscodemithra Ethnus Codemithra /ethnus /code_mithra

https://codemithra.com/vit-helpde
sk/

codemithra@ethnus.com +91 7815 095 095 +91 9019 921 340

You might also like