Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional
The string s = "abcbdab" needs characters deleted to become a palindrome. What is the minimum number of deletions? Use n minus the longest palindromic subsequence, computed by running the DP.
The string s = "abcbdab" needs characters deleted to become a palindrome. What is the minimum number of deletions? Use n minus the longest palindromic subsequence, computed by running the DP.
s="abcbdab"
n=len(s)
dp=[[0]*n for _ in range(n)]
for i in range(n-1,-1,-1):
dp[i][i]=1
for j in range(i+1,n):
dp[i][j]=dp[i+1][j-1]+2 if s[i]==s[j] else max(dp[i+1][j],dp[i][j-1])
print(n-dp[0][n-1])What is printed?- A. 5
- B. 4
- C. 3
- D. 2
Correct answer: D. 2
Deleting to a palindrome keeps a longest palindromic subsequence, so the deletions are n minus its length. Using the longest palindromic substring deletes too many characters, counting distinct letters is unrelated, and reporting the kept length is a misreading.
More Coding Interview Problems questions
- A 4×4 grid has rows "..#.", ".##.", "##.#", "#...". Entering a cell costs 1 if it is '#' and 0 otherwise, and you may move in four…
- Array c = [1, 2, 3, 0, 3, 3, 0, 6]. In how many ways can it be split into three non-empty contiguous parts whose sums are all equal? Run…
- Array d = [1, 2, 1, 3, 4, 3, 5]. Count the contiguous subarrays containing exactly three distinct values. Run the brute-force code. python…
- Houses have values e = [2, 7, 9, 3, 1, 8, 4, 6] and a robber cannot take two adjacent houses. Find the maximum sum that can be taken…
- Count the subarrays of v = [4, 6, 2, 1, 7, 3, 5, 1] whose XOR equals 0, considering only subarrays of length at least 3. Brute-force all…
- Histogram bars have heights h = [2, 1, 5, 6, 2, 3]. What is the area of the largest rectangle that fits entirely inside the histogram…