Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice
Problem: What is the length of the longest palindromic subsequence of 'character'? Run the DP.
Problem: What is the length of the longest palindromic subsequence of 'character'? Run the DP.
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] if L > 2 else 0) + 2
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return dp[0][n - 1]
print(lps('character'))What is printed?- A. 4
- B. 5
- C. 3
- D. 6
Correct answer: B. 5
The palindrome 'carac' (c, a, r, a, c) is the longest palindromic subsequence, with length 5.
More Coding Interview Problems questions
- Problem: What is the minimum number of characters to insert to make 'leetcode' a palindrome? Use length minus longest palindromic…
- Problem: How many binary strings of length 6 contain no three consecutive 1s? Run the code. python import itertools print(sum(1 for t in…
- Problem: How many derangements (permutations with no fixed point) of 1..6 exist? Run the code. python from itertools import permutations…
- Problem: How many permutations of 0..4 have exactly one inversion? Run the code. python from itertools import permutations print(sum(1 for…
- Problem: What is the smallest positive integer with exactly 10 positive divisors? Run the search. python n = 1 while sum(1 for d in…
- Problem: How many integers n in [1, 100] reach 1 under the Collatz map within 10 steps? Run the code. python def steps(n): c = 0 while n…