Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
Longest common subsequence: what is the length and one LCS read back from the table (preferring the upper cell on ties)?
Longest common subsequence: what is the length and one LCS read back from the table (preferring the upper cell on ties)?
a, b = "AGGTAB", "GXTXAYB"
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m):
for j in range(n):
dp[i+1][j+1] = dp[i][j] + 1 if a[i] == b[j] else max(dp[i][j+1], dp[i+1][j])
i, j, s = m, n, ""
while i and j:
if a[i-1] == b[j-1]: s = a[i-1] + s; i -= 1; j -= 1
elif dp[i-1][j] >= dp[i][j-1]: i -= 1
else: j -= 1
print(dp[m][n], s)- A. 4 GXAB
- B. 4 GTAB
- C. 3 GTB
- D. 5 GTAYB
Correct answer: B. 4 GTAB
The LCS length is 4 and the traceback yields GTAB (G, T, A, B appear in order in both strings). Subsequences may skip characters (X, Y in the second string). O(mn) time and space.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Edit distance between "kitten" and "sitting", and between "intention" and "execution". What is printed? python def ed(a, b): prev =…
- Matrix chain order for dimensions 5 × 10, 10 × 3, 3 × 12, 12 × 5, 5 × 50, 50 × 6. What is the minimum number of scalar multiplications?…
- What is printed? (level-order traversal of the BST built from these keys) python def insert(t, k): if t is None: return [k, None, None] i…
- What is printed? (inorder successor in a BST) python def insert(t, k): if t is None: return [k, None, None] i = 1 if k < t[0] else 2 t[i]…
- What is printed? (heap sort on a small array, showing the array after the first extraction) python def sift(a, i, n): while 2 i + 1 < n: c…
- What is printed? (trie: count distinct prefixes / nodes) python words = ["tea", "ten", "to", "inn", "in", "i"] root, nodes = {}, 0 for w…