Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the minimum number of characters to insert to make a string a palindrome.

Problem: Return the minimum number of characters to insert to make a string a palindrome.
def min_insert(s):
    t = s[::-1]; n = len(s)
    dp = [[0] * (n + 1) for _ in range(n + 1)]
    for i in range(n):
        for j in range(n):
            dp[i+1][j+1] = dp[i][j] + 1 if s[i] == t[j] else max(dp[i][j+1], dp[i+1][j])
    return n - dp[n][n]
print(min_insert("mbadm"), min_insert("leetcode"), min_insert("zzazz"))
What is printed?
  1. A. 2 6 0
  2. B. 3 5 0
  3. C. 2 5 0
  4. D. 2 5 1

Correct answer: C. 2 5 0

Insertions needed = n − (longest palindromic subsequence) = n − LCS(s, reverse(s)). "mbadm": LPS "mbm"/"mam" = 3 → 2. "leetcode": LPS "eee" = 3 → 5. Already a palindrome → 0. O(n²).

More Coding Interview Problems questions

Exams that ask this topic