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?- A. 2
- B. 0
- C. 1
- 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
- Problem: Find the next lexicographic permutation of the digits '1243' (the smallest permutation strictly greater than it). Run the code…
- Problem: Find the length of the longest substring of 'AABABBA' that can be made all one letter after at most k = 1 replacement. Run the…
- Problem: How many bits must be flipped to convert A = 29 into B = 15? Run the code. python A, B = 29, 15 print(bin(A ^ B).count('1')) What…
- Problem: What is printed by the stack-based decoder for '3[a2[c]]'? It expands k[s] to s repeated k times. python def decode(s): stack =…
- Problem: What is the minimum number of swaps needed to sort the permutation [4, 3, 2, 1] (values 1..4 each once)? Use the cycle…
- Problem: What is floor(sqrt(2000)) found by binary search? Run the code. python lo, hi = 0, 2000 while lo < hi: mid = (lo + hi + 1) // 2…