Longest Common Subsequence
Given two sequences X[1…n] and Y[1…m], a common subsequence is a sequence of characters appearing in both, in the same left-to-right order but not necessarily contiguously. For example, for X = BCDB and Y = ABDC, the string BD is a common subsequence of length 2. Design a dynamic-programming algorithm for the following task.
Note the CS6515 convention: LCS uses the plain-prefix subproblem — it does not force the last characters to be used. That "must include the last element" phrasing belongs to LIS, not LCS.
If the two current characters match, they extend the LCS of the smaller prefixes by 1. If they don't match, at least one of them is unused, so drop X[i] or Y[j] and take the better. All referenced cells have strictly smaller indices — well-defined, no self-reference.
Whenever a problem gives you two sequences/strings to match up, reach for T(i,j) indexed by a prefix of each, with the answer at the far corner T(n,m). Edit distance, sequence alignment (DPV 6.26), and longest common substring (DPV 6.8) are all this same engine with different cell rules.
Optional pseudocode not required by Ed #9
A mechanical translation of the recurrence. The exam grades the recurrence, not this.
function LCS(X[1..n], Y[1..m]): for i = 0 to n: L[i][0] = 0 for j = 0 to m: L[0][j] = 0 for i = 1 to n: for j = 1 to m: if X[i] == Y[j]: L[i][j] = 1 + L[i-1][j-1] else: L[i][j] = max(L[i-1][j], L[i][j-1]) return L[n][m]
Try it yourself
worked example + self-testMatch → 1+L(i−1,j−1) (diagonal); mismatch → max{above, left}. Answer L(n,m).
X = AGGTAB Y = GXTXAYB
GTAB (trace back diagonally on matches).X = BCDB Y = ABDCB
Reveal answer
BCB (also BDB is valid).