Data Structures & AlgorithmsModerateTCS NQT · DP warm-up
Problem: What is the length of the longest common subsequence of 'ABCBDAB' and 'BDCABA'?
Problem: What is the length of the longest common subsequence of 'ABCBDAB' and 'BDCABA'?
a, b = 'ABCBDAB', 'BDCABA'
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
print(dp[-1][-1])What is printed?- A. 3
- B. 4
- C. 5
- D. 6
Correct answer: B. 4
A longest common subsequence is BCBA, which appears in both strings in order, so the DP gives 4. Taking the longest common substring instead gives a smaller value.
More Coding Interview Problems questions
- Problem: The number of structurally distinct binary search trees on 5 keys is the Catalan number. What does this code print? python dp =…
- Problem: What is the sum over all pairs (i < j) of the Hamming distances (number of differing bits) between the values in [1, 3, 5]? Run…
- Problem: People with weights [3, 2, 2, 1] must cross a river. A boat carries at most 2 people with total weight at most limit = 3, and…
- Problem: Koko eats bananas from piles [3, 6, 7, 11] and has h = 8 hours. She picks one pile per hour and eats up to k bananas from it…
- Problem: How many primes are there up to 100? Run the sieve. python n = 100 sieve = [True] (n + 1) sieve[0] = sieve[1] = False for i in…
- Problem: How many ways can the digit string '226' be decoded when 1 maps to A, 2 to B, ..., 26 to Z? Run the DP. python s = '226' dp = [1]…