GATE Computer Science · Programming, Data Structures, and Algorithms · medium
What is the length of the Longest Common Subsequence (LCS) of the two strings X = 'ABCBDAB' and Y = 'BDCABA'?
Published · Last updated · checked before publication — how we verify questions
Options
Answer: B. 4 (with valid longest common subsequences including 'BCBA' and 'BDAB')
The LCS of X = ABCBDAB and Y = BDCABA has length 4. A subsequence keeps characters in the same relative order but need not be contiguous. BCBA appears in X at positions 2, 3, 4, 6 and in Y at positions 1, 3, 5, 6. BDAB appears in X at positions 2, 5, 6, 7 and in Y at positions 1, 2, 4, 5. BCAB is also valid. The standard DP table uses L[i][j] = L[i-1][j-1] + 1 when X[i] equals Y[j], and otherwise max(L[i-1][j], L[i][j-1]). Filling it gives L[7][6] = 4. This is the textbook example, and its answer is 4. The common trap is mixing up subsequence with substring, or counting matching letters without enforcing order in both strings. The LCS is also not unique, but its length is always 4, and the question asks only for the length. Length 5 would need five characters in matching order in both strings, and the table shows none exists.
Why the other options are wrong
- A. 3 because the longest contiguous common substring has length 2 ('AB') — This describes the longest common substring, which must be contiguous. LCS allows gaps, so the contiguous length of 2 is irrelevant, and the true LCS length is 4, not 3.
- C. 5 obtained by counting repeated characters in X ignoring index order in Y — Counting repeated characters while ignoring their order in Y does not give a subsequence. An LCS must appear in increasing index order in both strings, and under that constraint the maximum is 4, not 5.
- D. 6 equal to the full length of the shorter input string Y = 'BDCABA' — This would hold only if Y = BDCABA were itself a subsequence of X. It is not, because X has no B, D, C, A, B, A in that order, so the LCS is shorter than Y.
More Programming, Data Structures, and Algorithms questions
- For Quicksort using deterministic last-element pivoting on an array of n distinct elements that is already sorted in…
- Consider the recurrence relation T(n) = 4T(n / 2) + n^2 for n > 1, with T(1) = 1. Using the Master Theorem, what is…
- Which two statements accurately compare Dijkstra's single-source shortest-path algorithm and the Bellman-Ford…
- A message uses five characters A, B, C, D, and E with frequencies 5, 9, 12, 13, and 16 respectively. Using optimal…
All Programming, Data Structures, and Algorithms questions and the topic overview →
GATE is a mark of the Indian Institute of Science and the Indian Institutes of Technology. PrepIQ Hub is not affiliated with, endorsed by, or sponsored by the GATE Committee.