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)
  1. A. 4 GXAB
  2. B. 4 GTAB
  3. C. 3 GTB
  4. 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.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic