Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Find the length of the longest common subsequence of two version strings.
Problem: Find the length of the longest common subsequence of two version strings.
def lcs(a, b):
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):
dp[i][j] = dp[i-1][j-1] + 1 if a[i-1] == b[j-1] else max(dp[i-1][j], dp[i][j-1])
return dp[-1][-1]
print(lcs("ABCBDAB", "BDCABA"), lcs("abc", "def"))What is printed?- A. 3 0
- B. 4 0
- C. 5 0
- D. 4 1
Correct answer: B. 4 0
dp[i][j] = LCS of the first i and j characters. One LCS is BCBA (or BDAB) of length 4. Subsequences need not be contiguous – the longest common substring here is only 2. O(m·n) time and space (O(min) with two rows).
More Coding Interview Problems questions
- Problem: Find the minimum number of insert, delete or replace operations to convert one word to another (edit distance). python def…
- Problem: Count paths from the top-left to the bottom-right of a grid moving only right or down, where 1 marks a blocked cell. python def…
- Problem: Find the minimum path sum from the top-left to the bottom-right of a cost grid (moves: right or down). python def minpath(g): R…
- Problem: Count the ways to decode a digit string where 'A' = 1 … 'Z' = 26. python def decode(s): prev2, prev1 = 1, (1 if s[0] != '0' else…
- Problem: Decide whether a string can be split into words from a dictionary. python def wb(s, words): W = set(words); dp = [True] + [False]…
- Problem: Return the maximum product of a contiguous subarray (values may be negative or zero). python def maxprod(a): hi = lo = best =…