Skip to content
Official PYQ · 2009

GATE CS 2009 Q53 — Algorithm Design: Dynamic Programming

Explain with AI

A sub-sequence of a given sequence is just the given sequence with some elements (possibly none or all) left out. We are given two sequences X[m]X[m] and Y[n]Y[n] of lengths mm and nn, respectively with indexes of XX and YY starting from 00.

We wish to find the length of the longest common sub-sequence (LCS) of X[m]X[m] and Y[n]Y[n] as l(m,n)l(m, n), where an incomplete recursive definition for the function I(i,j)I(i, j) to compute the length of the LCS of X[m]X[m] and Y[n]Y[n] is given below:

l(i,j)  = 0, if either i = 0 or j = 0
        = expr1, if i,j > 0 and X[i-1] = Y[j-1]
        = expr2, if i,j > 0 and X[i-1] ≠ Y[j-1]

Which one of the following options is correct?

Choose one option
View worked solution

Answer: C

The function l(i,j)l(i, j) represents the length of the Longest Common Subsequence (LCS) of the prefixes X[0…i−1]X[0 \dots i-1] and Y[0…j−1]Y[0 \dots j-1].

We can formulate the recurrence relation by analyzing the last characters of the prefixes, namely X[i−1]X[i-1] and Y[j−1]Y[j-1]:

  1. Case 1: The last characters match (X[i−1]=Y[j−1]X[i-1] = Y[j-1])

    Since the characters match, they must be part of the LCS. Thus, the length of the LCS increases by 11, and we recursively find the LCS of the remaining prefixes of lengths i−1i-1 and j−1j-1:

    expr1=l(i−1,j−1)+1\text{expr1} = l(i-1, j-1) + 1
  2. Case 2: The last characters do not match (X[i−1]≠Y[j−1]X[i-1] \neq Y[j-1])

    Since the characters do not match, both cannot simultaneously be part of the LCS. The optimal solution is the maximum of two possibilities:

    • Excluding X[i−1]X[i-1]: l(i−1,j)l(i-1, j)
    • Excluding Y[j−1]Y[j-1]: l(i,j−1)l(i, j-1)

    Thus, the recurrence is:

    expr2=max⁡(l(i−1,j),l(i,j−1))\text{expr2} = \max\left(l(i-1, j), l(i, j-1)\right)

Comparing these with the given options:

  • Option A is incorrect because expr1\text{expr1} should be l(i−1,j−1)+1l(i-1, j-1) + 1.
  • Option B is incorrect.
  • Option C correctly matches our formulation for expr2\text{expr2}.
  • Option D is incorrect.

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

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