Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Find the length of the longest palindromic subsequence of s and the minimum number of insertions that make s a palindrome.

Problem: Find the length of the longest palindromic subsequence of s and the minimum number of insertions that make s a palindrome.
def lps(s):
    n = len(s); dp = [[0] * n for _ in range(n)]
    for i in range(n - 1, -1, -1):
        dp[i][i] = 1
        for j in range(i + 1, n):
            dp[i][j] = dp[i+1][j-1] + 2 if s[i] == s[j] else max(dp[i+1][j], dp[i][j-1])
    return dp[0][n-1]
s = "character"
L = lps(s)
print(L, len(s) - L)
What is printed?
  1. A. 3 6
  2. B. 4 5
  3. C. 5 4
  4. D. 6 3

Correct answer: C. 5 4

The longest palindromic subsequence of 'character' is 5 (e.g. 'carac'). Every character outside it needs a mirrored partner, so the minimum insertions are n − LPS = 9 − 5 = 4.

More Coding Interview Problems questions

Exams that ask this topic