Data Structures & AlgorithmsVery hardICPC regional · string DP

Problem: The minimum number of insertions to make 'abcab' a palindrome equals n minus the length of its longest palindromic subsequence. What does this code print?

Problem: The minimum number of insertions to make 'abcab' a palindrome equals n minus the length of its longest palindromic subsequence. What does this code print?
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 = 'abcab'
print(len(s) - lps(s))
What is printed?
  1. A. 3
  2. B. 1
  3. C. 4
  4. D. 2

Correct answer: D. 2

The longest palindromic subsequence of abcab has length 3 (for example aba), so 5 - 3 = 2 insertions are needed. Using the length of the longest palindromic substring instead gives a different count.

More Coding Interview Problems questions

Exams that ask this topic