Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

For the string "character", find the length of its longest palindromic subsequence (characters need not be adjacent, but must keep their relative order).

For the string "character", find the length of its longest palindromic subsequence (characters need not be adjacent, but must keep their relative order).
s="character"
n=len(s)
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 s[i]==s[j]: dp[i][j]=dp[i+1][j-1]+2 if L_>2 else 2
        else: dp[i][j]=max(dp[i+1][j],dp[i][j-1])
print(dp[0][n-1])
What is printed?
  1. A. 5
  2. B. 3
  3. C. 4
  4. D. 6

Correct answer: A. 5

The palindromic-subsequence DP matches equal outer characters and otherwise drops one end, taking the max. The longest palindromic substring is contiguous and is only 3 here, LCS of the string with its reverse must not lose the final match, and adding one to the DP value is a stray off-by-one.

More Coding Interview Problems questions

Exams that ask this topic