Skip to content
Official PYQ · 2014

GATE CS 2014 Set 2 Q37 — Algorithm Design: Dynamic Programming

Explain with AI

Consider two strings AA = "qpqrr" and BB = "pqprqrp". Let xx be the length of the longest common subsequence (not necessarily contiguous) between AA and BB and let yy be the number of such longest common subsequences between AA and BB. Then x+10y=x +10y= ___.

View worked solution

Answer: 34

To find the length (xx) and the number (yy) of the longest common subsequences (LCS) between A="qpqrr"A = \text{"qpqrr"} and B="pqprqrp"B = \text{"pqprqrp"}:

Since the length of AA is 55, any subsequence of AA of length 44 is obtained by deleting exactly one character from AA. Let's list all unique subsequences of AA of length 44:

  • Delete 1st1^{\text{st}} character (qq): "pqrr"
  • Delete 2nd2^{\text{nd}} character (pp): "qqrr"
  • Delete 3rd3^{\text{rd}} character (qq): "qprr"
  • Delete 4th4^{\text{th}} or 5th5^{\text{th}} character (rr): "qpqr"

Now, we check which of these are also subsequences of B="pqprqrp"B = \text{"pqprqrp"}:

  1. "pqrr": Yes, matched at indices 1,2,4,61, 2, 4, 6 of BB (p‾q‾pr‾qr‾p\underline{p}\underline{q}p\underline{r}q\underline{r}p).
  2. "qqrr": No, because matching two qq's (at indices 22 and 55) leaves only one rr (at index 66) before the end of BB.
  3. "qprr": Yes, matched at indices 2,3,4,62, 3, 4, 6 of BB (pq‾p‾r‾qr‾pp\underline{q}\underline{p}\underline{r}q\underline{r}p).
  4. "qpqr": Yes, matched at indices 2,3,5,62, 3, 5, 6 of BB (pq‾p‾rq‾r‾pp\underline{q}\underline{p}r\underline{q}\underline{r}p).

The only subsequence of length 55 is AA itself, which is not a subsequence of BB. Thus, the length of the LCS is x=4x = 4, and the number of distinct longest common subsequences is y=3y = 3 (which are "pqrr", "qprr", and "qpqr").

Calculating the required value:

x+10y=4+10(3)=34x + 10y = 4 + 10(3) = 34

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Algorithm Design: Dynamic Programming questions