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?- A. 3
- B. 1
- C. 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
- Problem: Count pairs (i < j) of a = [1, 2, 3] with a[i] XOR a[j] summed over all pairs. What is the total of the XOR values? Run the code…
- Problem: What is the maximum sum of a path from the top-left to the bottom-right of the grid [[1,3,1],[1,5,1],[4,2,1]] moving only right…
- Problem: How many binary strings of length 5 contain no two consecutive 1s?
- Problem: What is the maximum product of a non-empty contiguous subarray of [2, 3, -2, 4, -1]? Use the code below. python a = [2, 3, -2, 4…
- Problem: How many islands (4-connected groups of '1') are in the grid below? Run the DFS code. python g = ['11000', '11000', '00100'…
- Problem: How many subarrays of [1, -1, 2, -2, 3, -3] have sum zero? Run the prefix-count code. python from collections import Counter a =…