Data Structures & AlgorithmsHardICPC regional · string DP

Problem: What is the length of the longest palindromic subsequence of 'bbbab'?

Problem: What is the length of the longest palindromic subsequence of 'bbbab'?
def lps(s):
    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])
    return dp[0][n - 1]
print(lps('bbbab'))
What is printed?
  1. A. 4
  2. B. 3
  3. C. 5
  4. D. 2

Correct answer: A. 4

The subsequence 'bbbb' is a palindrome of length 4 and no 5-letter subsequence works. Using the substring DP instead of the subsequence DP would give a smaller answer.

More Coding Interview Problems questions

Exams that ask this topic