Data Structures & AlgorithmsModerateProduct Company SDE · string DP

Problem: What is the minimum number of deletions to make the string 'abcca' a palindrome? Use the palindromic-subsequence DP and print len(s) minus its length.

Problem: What is the minimum number of deletions to make the string 'abcca' a palindrome? Use the palindromic-subsequence DP and print len(s) minus its length.
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]
s = 'abcca'
print(len(s) - lps(s))
What is printed?
  1. A. 2
  2. B. 0
  3. C. 1
  4. D. 3

Correct answer: C. 1

The longest palindromic subsequence 'acca' has length 4, so deleting one character (the b) gives a palindrome. Two deletions would be needed only if the subsequence had length 3.

More Coding Interview Problems questions

Exams that ask this topic