Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional
For the string "character", find the length of its longest palindromic subsequence (characters need not be adjacent, but must keep their relative order).
For the string "character", find the length of its longest palindromic subsequence (characters need not be adjacent, but must keep their relative order).
s="character"
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])
print(dp[0][n-1])What is printed?- A. 5
- B. 3
- C. 4
- D. 6
Correct answer: A. 5
The palindromic-subsequence DP matches equal outer characters and otherwise drops one end, taking the max. The longest palindromic substring is contiguous and is only 3 here, LCS of the string with its reverse must not lose the final match, and adding one to the DP value is a stray off-by-one.
More Coding Interview Problems questions
- Count the subarrays of w = [1, 3, 2, 5, 4, 4, 2] whose maximum minus minimum is at most 3. Run the brute-force count. python…
- What is the minimum number of perfect squares (1, 4, 9, 16, ...) whose sum is exactly 12? Run the DP over all squares not exceeding 12…
- Count the subsequences (by position, not distinct strings) of "abcabc" that equal "abc". Run the DP that counts matches. python…
- Array a = [2, 3, 1, 1, 4, 2, 0, 3, 1, 1]; from index i you may jump to any index in [i+1, i+a[i]]. Find the minimum number of jumps from…
- Trapping rain water: heights h = [4, 2, 0, 3, 2, 5, 1, 0, 2]. Compute the total water trapped between the bars. python…
- The permutation p = [4, 3, 1, 7, 6, 2, 5] of 1..7 must be sorted by swaps of any two elements. What is the minimum number of swaps?…