Data Structures & AlgorithmsHardICPC regional · string DP
Problem: What is the length of the longest palindromic subsequence of 'bbbab'?
Problem: What is the length of the longest palindromic subsequence of 'bbbab'?
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]
print(lps('bbbab'))What is printed?- A. 4
- B. 3
- C. 5
- D. 2
Correct answer: A. 4
The subsequence 'bbbb' is a palindrome of length 4 and no 5-letter subsequence works. Using the substring DP instead of the subsequence DP would give a smaller answer.
More Coding Interview Problems questions
- Problem: Multiply a chain of matrices with dimensions p = [10, 30, 5, 60] (matrix i is p[i] by p[i+1]). Find the minimum number of scalar…
- Problem: How many ways can 10 be formed as an ordered-free sum of coins 1, 2 and 5 (each coin may be used any number of times, and order…
- Problem: What is the diameter (in edges) of the tree with edges 1-2, 2-3, 2-4, 4-5, 5-6? Use the double BFS code. python from collections…
- Problem: A robot starts at (0, 0) facing north (+y). Commands: F moves one step forward, B one step backward (facing unchanged), L turns…
- Problem: What is the KMP prefix-function array pi for the string 'ababaca'? python s = 'ababaca' pi = [0] len(s) for i in range(1…
- Problem: What is the lexicographically smallest rotation of 'bcabca'? python s = 'bcabca' print(min(s[i:] + s[:i] for i in range(len(s))))…