Question
Consider two strings and . Let be the length of the longest common subsequence (not necessarily contiguous) between and and let be the number of such longest common subsequences between and . Then _____.
Official answer and solution
- Official answer
- 34
- From
- Official GATE 2014 answer key
Solution
Determine the Longest Common Subsequence length using dynamic programming and enumerate distinct maximal subsequences.
-
Given Strings:
-
Finding LCS Length :
Constructing the DP table for lengths:- Subsequences of length 4:
- Check
qprr: in , indices are (q,q,r,rwith matchingqat 0,pat 1,rat 3,rat 4); in ,qat 1,pat 2,rat 3,rat 5. Match found! - Check
qpqr: in ,q(0),p(1),q(2),r(3); in ,q(1),p(2),q(4),r(5). Match found! - Check
pqrr: in ,p(1),q(2),r(3),r(4); in ,p(0),q(1),r(3),r(5). Match found!
- Check
- Can we form length 5? The only length-5 subsequence of is itself (
qpqrr). Looking forqpqrrin : firstqis at index 1, nextpat index 2, nextqat index 4, nextrat index 5. But has no secondrafter index 5! So length 5 is impossible. - Thus, maximum length .
- Subsequences of length 4:
-
Enumerating Distinct LCS of Length 4 ():
The 4-character subsequences of are:- Dropping index 0 (
q):pqrr(present in ) - Dropping index 1 (
p):qqrr(not in , since has only oneqbeforer) - Dropping index 2 (
q):qprr(present in ) - Dropping index 3 (
r):qpqr(present in ) - Dropping index 4 (
r):qpqr(duplicate)
Thus, there are exactly 3 distinct LCS strings:{"qprr", "qpqr", "pqrr"}.
- Dropping index 0 (
-
Computing :
34
Counting identical subsequence strings multiple times due to multiple index paths rather than distinct strings.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2014 Computer Science and Information Technology (CS) Session 2
- Question
- 47 of 65, printed as CS Q.37
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.