Longest Common Subsequence (LCS)

Context: FIT2004_MOC · the two-prefix grid — the shape behind LCS, shortest common supersequence, interleaving and edit distance Parent Framework: Dynamic Programming

Quick Revision

  • 🎯 Objective: over the prefixes and ➔ characters match ⟹ consume both and ; they differ ⟹ try dropping each, take the better.
  • 📦 Core Components: subproblems ➔ each ⟹ time and space | answer at | .
  • ⚡ Key Constraint: a subsequence deletes but never reorders — it is not a substring. The whole recurrence rests on “if the two prefixes end in the same character, that character can be taken as the last element of a common subsequence.”

📝 How It Works

1. Why Prefixes Are the Right Subproblems

  • The observation ➔ let be the final element of an LCS, occurring at position in and in . Then must be an LCS of and — otherwise a longer one would extend .
  • Consequence ➔ the subproblems are prefixes of both sequences, i.e. a 2-D grid indexed by one cut point per sequence.
  • Edit distance shares this exact grid ➔ the applied sheet’s hint says LCS is “very similar to the edit distance problem”, and the DP lecture deliberately skips edit distance, deferring it to the tutorial videos “linking it up with the longest common subsequence (LCS) problem there” — so this note is where edit distance lands. Same subproblems, different payload: LCS counts matches, edit distance counts insert / delete / replace operations.
  • The MEMO sentence ➔ DP[i][j] = {the length of a longest common subsequence of a[1..i] and b[1..j]} for , .
  • The zero row and column are real cells ➔ index from , not ; an empty prefix is a legitimate subproblem and is where the base case lives.

2. The Recurrence

  • Match ⟹ consume both ➔ no need to also try dropping one; keeping a matched pair never loses.
  • Mismatch ⟹ one of them cannot be last ➔ and differ, so at most one can end the common subsequence; try removing each and take the better.
  • Answer ➔ — unlike LIS, no scan, because the subproblem is not anchored to a last element.
  • Cost ➔ subproblems time, space.

3. Shortest Common Supersequence — Solve It by Reduction (applied P11)

  • Definition ➔ a supersequence of contains as a subsequence; the SCS of is the shortest sequence containing both.
  • The identity ➔ : the SCS must contain the LCS, and every shared character is written once instead of twice.
  • So the whole problem is one subtraction ➔ , no new algorithm.
  • The direct DP, if asked for it
  • Compare the two recurrences side by side ➔ the bases change from to “copy what is left”, and the mismatch case flips to . Everything else is identical — that similarity is the marked observation (LO1).

4. Interleaving — the Same Grid With the Third Index Deleted (applied P13)

  • Problem ➔ given (), () and (), decide whether interleaves and .
  • The naive subproblem carries three indices ➔ DP[i][j][k] = {can A[i..n] and B[j..m] be interleaved to form C[k..n+m]?} ⟹ subproblems.
  • The elimination ➔ having consumed up to in and in , you are necessarily at position in ⟹ is redundant, and suffices ➔ . Same move as the ferry problem ➔ Dynamic Programming §5.
  • The recurrence is a boolean or ➔ try taking the next character from , and from ; either working is enough.
  • Answer ➔ ; subproblems at .

⚙️ Core Implementation

🔹 LCS length reconstruction

🔭 Beyond the lecture (not in the slides): only the previous row is ever read, so the length can be computed in space with two rolling rows. Reconstruction still needs the full table, so do not offer the rolling version when the question asks which characters.

⚖️ Complexity

ProblemTimeAuxiliary spaceAnswer cell
LCS length
LCS reconstructiontable reusedwalk back from
SCS by reduction
Interleaving (3 indices)— do not stop here
Interleaving (2 indices)

📊 Exam Execution Trace & Applied Exercises

Manual Execution Trace

(rows), (columns). Matches are bold.

Final Extracted Output: . Backtracking with tie-break “prefer up on ”: match match , reversed . Also valid: — ties give different LCSs of the same length. , e.g. .

  • Read the shape ➔ a match steps diagonally; a mismatch steps up or left. A diagonal step is the only one that emits a character.
  • Read the trap ➔ the table is non-decreasing left-to-right and top-to-bottom, so the corner really is the maximum — this is exactly why LCS needs no scan and LIS does.

Applied Exercise — derive the SCS identity (P11)

Problem: prove .

Final Extracted Output: the SCS problem is without a new recurrence. The reusable move (LO1): before writing a DP, check whether the quantity asked for is an arithmetic function of one you already know how to compute.

⚠️ Common Mistakes

  • 💡 Treating subsequence as substring ➔ a subsequence may skip; a substring may not. The recurrence for contiguous ranges is a different note ➔ Interval Dynamic Programming.
  • 💡 Also trying the drop-one branches on a match ➔ harmless but wasteful, and it invites a wrong max that undercounts; on the diagonal branch is provably optimal.
  • 💡 Keeping the third index in the interleaving problem ➔ where was asked for; is forced ➔ Dynamic Programming §5.
  • 💡 Reporting the LCS as unique ➔ the length is unique, the subsequence is not — say “an” LCS, and state your tie-break, exactly as for an MST.
  • 💡 Rolling the rows and then asking for the characters ➔ the -space version destroys the reconstruction path.

🧠 Active Recall