Data Structures & AlgorithmsModerateTCS NQT · string round
Problem: Find the length of the longest common substring (contiguous) of 'abcdef' and 'zcdemn'.
Problem: Find the length of the longest common substring (contiguous) of 'abcdef' and 'zcdemn'.
def lcs_sub(a, b):
best = 0
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
best = max(best, dp[i][j])
return best
print(lcs_sub('abcdef', 'zcdemn'))What is printed?- A. 2
- B. 4
- C. 3
- D. 5
Correct answer: C. 3
The shared contiguous block is 'cde', giving 3. A longest common subsequence would also allow gaps, which is why the DP resets on mismatch.
More Coding Interview Problems questions
- Problem: How many (possibly overlapping) occurrences of the pattern 'ana' are in 'banana'? python s = 'banana' p = 'ana' print(sum(1 for i…
- Problem: Each element of [2, 3, 1, 1, 4] is the maximum jump length from that index. What is the minimum number of jumps to reach the last…
- Problem: A circular route has gas = [1, 2, 3, 4, 5] and cost = [3, 4, 5, 1, 2] (cost to travel from station i to i+1). Find the start…
- Problem: What is the minimum number of intervals to remove so that the rest are pairwise non-overlapping (touching at an endpoint is…
- Problem: The prefix sums of [2, 5, 1, 7, 3] are stored in a list p. What is printed by the code, which finds the first index whose prefix…
- Problem: Arrange the numbers 3, 30, 34, 5, 9 so that the concatenation is the largest possible. Run the code and state the printed string…