One word swapped for another, one requirement dropped.
Crucial contrast: a substring is a subsequence whose kept
elements are also contiguous (no gaps). "ACE" is a subsequence of
"ABCDE" but not a substring of it. LCS never requires contiguity.
Same distinction, on real letters: "BD" is a subsequence of "ABCBD"
(delete A and C) but not a substring of it (C sits between B and D).
CLRS (Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms) 4th ed - Ch 14, Section 14.4 (Longest common subsequence).
Key Words Today
Prefix: the first elements of a sequence, written - the DP table's "how far in" axis.
Optimal substructure: an optimal solution to a problem contains optimal solutions to its subproblems - what makes DP possible at all.
Overlapping subproblems: the same smaller subproblem gets needed again and again - what makes a table (not fresh recursion) worthwhile.
Recurrence relation: the equation defining a table cell's value from other cells already computed.
The Problem, Precisely - and Why Not Brute-Force
Time to build the actual algorithm.
Input: two sequences and . Output: the length of their
longest common subsequence - and the actual subsequence itself,
reconstructed.
A brute-force idea: generate every subsequence of , check each
against . has subsequences - one for every possible
subset of its positions kept or dropped. For CampusNav's course lists
(), that's already over 4,000 checks, and every
additional class either student adds doubles that count - the
same exponential shape as Week 4's runaway recursion trees and Week
11's naive Fibonacci call tree. We need the answer without ever
generating a single subsequence by hand.
Optimal Substructure: The Matching Case
The key insight, argued carefully - not asserted.
Let = length of the LCS of and .
If : this matched pair can always be the last
element of some LCS of - if an optimal common
subsequence didn't already end there, we could append this shared
element to it and get a strictly longer one, a contradiction (the
contradiction move from Week 7).
Optimal Substructure: The Mismatch Case
The other half of the argument.
If : the LCS cannot use both and as
its final matched element - they aren't equal, so they can't be the same matched pair. So the best answer either drops or drops from consideration, whichever choice leaves the longer match:
Dropping both and at once is never necessary - keeping
at least one of them available can only help, never hurt.
The Recurrence, Formalized
Same two cases, now as one equation.
Base case, why 0: an empty prefix (of either sequence) shares no
elements with anything - there's nothing to match. A symmetry
worth noting: swapping which sequence is labeled and which is transposes the table's shape, but changes neither the recurrence
nor the final LCS length.
Why Row-by-Row Filling Works
The equation only helps if we can actually compute it, in order.
Every cell depends only on cells above it (), to its left (), or diagonally above-left
() - never on a cell below or to the right of it.
Fill row 0 and column 0 first (the base case), then sweep the
table row by row, left to right: every dependency a cell needs is
already computed by the time that cell is reached.
(m+1) × (n+1) cells, each computed in O(1)
Building the Table: The Procedure
1
Make an (m+1) × (n+1) grid. Row 0 and column 0 are the empty-prefix baseline: fill them with 0.
2
For i = 1 to m, for j = 1 to n (row by row): if X[i] = Y[j], set L(i,j) = L(i-1,j-1) + 1.
3
Otherwise, set L(i,j) = max(L(i-1,j), L(i,j-1)).
4
L(m,n), the bottom-right corner, is the length of the LCS of the full X and Y.
Memoization vs. Tabulation for LCS
Two bookkeeping styles, the exact same L(i,j) recurrence.
Memoization (top-down)
LCS_MEMO(X, Y, i, j, cache):
if i == 0 or j == 0:
return 0
if cache[i][j] is set:
return cache[i][j]
if X[i] == Y[j]:
cache[i][j] =
LCS_MEMO(X,Y,i-1,j-1,cache) + 1
else:
cache[i][j] = max(
LCS_MEMO(X,Y,i-1,j,cache),
LCS_MEMO(X,Y,i,j-1,cache))
return cache[i][j]
Tabulation (bottom-up)
LCS_TAB(X, Y, m, n):
L[0][*] = 0, L[*][0] = 0
for i = 1 to m:
for j = 1 to n:
if X[i] == Y[j]:
L[i][j] = L[i-1][j-1] + 1
else:
L[i][j] = max(L[i-1][j],
L[i][j-1])
return L[m][n]
Same recurrence, same distinct subproblems, same
time. Only the direction differs - exactly like Week 11's Fibonacci.
LCS · worked example 1 of 3 (simple)
The Smallest Case: X = AC, Y = CA
Two letters each. Enough to need the full recurrence - and enough to already show a tie.
GoalFill the 3×3 table of L(i,j) using only the two-case recurrence.
1
Setup
X=AC, Y=CA. Base row/column are 0. Fill L(1,1), L(1,2), L(2,1), L(2,2) in order.
→
2
Fill the cells
L(1,1): A vs C, mismatch, max(0,0)=0. L(1,2): A vs A, match, L(0,1)+1=1. L(2,1): C vs C, match, L(1,0)+1=1. L(2,2): C vs A, mismatch, max(1,1)=1.
→
3
Result
LCS length = 1. Two different one-letter answers both work ("A" or "C") - a tie.
✓
ConclusionLCS(AC, CA) = 1 - already a tie between two different valid answers, previewing today's harder tier.
💡
Key takeawayEven a 2-letter pair needs the full recurrence, not intuition - and already shows LCS answers aren't always unique.
LCS · worked example 2 of 3 (moderate)
Full Trace: X = ALGDP, Y = ALGRDP
The first five and six course codes of Minji's and Junho's real sequences.
GoalFill all 42 cells using only the recurrence, row by row.
ε
A
L
G
R
D
P
ε
0
0
0
0
0
0
0
A
0
1
1
1
1
1
1
L
0
1
2
2
2
2
2
G
0
1
2
3
3
3
3
D
0
1
2
3
3
4
4
P
0
1
2
3
3
4
5
✓
ConclusionL(5,6) = 5 - 42 cells, filled row by row.
💡
Key takeawayEvery cell needs only three neighbors already on the table.
LCS · worked example 2 of 3 (moderate), continued
Full Trace, Continued: Reading Two Key Cells
Same table as the previous slide. Here's exactly how two of its cells were filled.
GoalShow the recurrence's two cases at work on real cells from the table.
1
Matches extend the diagonal
L(2,2): X[2]=L, Y[2]=L, match → L(1,1)+1 = 1+1 = 2.
Bottom-right (blue): L(5,6) = 5 - the full LCS of ALGDP and ALGRDP has length 5.
✓
ConclusionEvery cell in the table follows the same two-case recurrence, whether it's a clean diagonal match or a mismatch reaching sideways.
💡
Key takeawayReading a filled table backward, cell by cell, is exactly how you'd check a claimed answer's work.
LCS · worked example 3 of 3 (harder)
Traceback: Reconstructing the Actual Sequence
The table gives a length. Traceback gives the actual matched letters - and shows what a tie really means.
GoalWalk L(5,6) backward to (0,0), and find a genuine tie elsewhere in the same table.
1
The procedure
Start at (m,n). If X[i]=Y[j], record it, move diagonally to (i-1,j-1). Otherwise move to whichever of (i-1,j)/(i,j-1) is larger. Stop at i=0 or j=0; reverse what was recorded.
L(4,4) (row D, col R): neighbors L(3,4)=3 and L(4,3)=3, equal. If traceback passed through here, either direction gives a different, equally valid length-3 common subsequence.
★
What a tie means
Not a bug: it's the table correctly reporting more than one longest common subsequence exists. Any consistent tie-breaking rule (e.g. "prefer up") produces one valid answer; a different rule produces a different, equally valid one.
✓
ConclusionTraceback reconstructs A-L-G-D-P, not just the number 5 - and the table's one genuine tie (L(4,4)) shows ties are a real, expected feature of LCS, not an edge case to avoid.
💡
Key takeawayA DP table doesn't just prove a length is optimal - traceback is what turns that proof into the actual answer.
Complexity
Last piece: how much does this cost? (Big-O can take more than one variable - $O(mn)$ tracks two input sizes at once, not just one $n$.)
Time: O(mn). Each of the (m+1)(n+1) cells is filled in O(1) from already-computed neighbors - total work is proportional to the number of cells.
Space: O(mn). The full table must be kept if you need the traceback (the actual subsequence). Refinement: if only the length is needed, only the previous row must be kept - space. CampusNav's traceback needs the real string, so it keeps the full table.
O(mn) time · O(mn) space (with traceback)
Compare to brute force's - checking every subsequence
of against . DP turns exponential into polynomial, same as
every paradigm this course has built since Week 9.
CampusNav: Find a Study Buddy
Everything above, on the actual feature.
Minji's and Junho's real weekly course-code sequences:
The short pair just traced by hand, ALGDP / ALGRDP, is literally
the first five and six codes of these two real sequences - you've
already solved a prefix of CampusNav's real problem. Building the
full 12×11 table and traceback for these exact sequences is Assignment 4, Task 1 (released Week 13, due Week 15). Once solved, CampusNav can
finally tell Minji and Junho exactly which courses they share, and
in what order - not "no match."
Common Mistakes
Subsequence vs. substring. LCS does not require the shared
elements to be contiguous. It's tempting because the word "sequence"
sounds like it should mean an unbroken run - but "ACE" is a valid
common subsequence of "ABCDE" and "XAYCZE" even though neither
contains "ACE" as a contiguous block. If you catch yourself checking
for a shared block of characters, you've quietly solved the wrong
(easier, less useful) problem.
Memoization vs. tabulation. A confusion this course has now
flagged twice - Week 11 and today. They're the same recurrence - the
top-down (memoized) version caches results the first time they're
needed; the table filled by hand above is the bottom-up (tabulated)
version of the exact same equation. The two code blocks a
few slides back are proof: same cases, same base case, same final
answer - only the direction of computation differs.
Key Words Today
LCS (Longest Common Subsequence): the longest sequence that is a subsequence of two given sequences at once.
Traceback: walking a filled DP table backward from its corner to reconstruct an actual optimal solution, not just its value.
Edit distance / sequence alignment: related problems (how many insertions/deletions/substitutions turn one sequence into another) solved with a close cousin of today's recurrence - used in diff, spell-checkers, and DNA comparison.
2-D DP: dynamic programming where the subproblem needs two indices, one per sequence - today's structural upgrade from Week 11's 1-D tables.
LCS vs. Edit Distance: How Related?
The Key Words slide just named a close cousin. Here's exactly how close.
Edit distance counts insertions, deletions, and substitutions needed
to turn one string into another. A longer LCS generally means a
smaller edit distance - more shared structure means fewer changes
needed - but the two are related, not identical: edit distance's
recurrence also allows a substitution move (swap one character for
another) that LCS's recurrence has no equivalent for - LCS only ever
matches exactly or drops a character. So the two problems are solved
by closely related, but not identical, recurrences. CLRS covers edit
distance (sequence alignment) as the natural next topic after LCS,
for exactly this reason.
CampusNav: One App, Two DP Weeks
Where Weeks 11-12 sit in the whole build.
Wks 1-7
Directory lookup: sort + search the room list
›
Wks 9-10
Free-time finder, room-booking scheduler
›
Wks 11-12
Tour Planner (1-D DP), study-buddy matching (2-D DP)
›
Wks 13-14
Campus map + Get Directions
Two weeks, one paradigm, two shapes of table - CampusNav now
optimizes over one sequence and compares two.
Why This Shows Up in Interviews, Too
This isn't only about CampusNav.
LCS is one of the most frequently asked dynamic programming
interview questions at every major tech company - precisely because
it forces you to justify a 2-D recurrence from scratch, not just
recite one. The same skeleton (define , find the recurrence,
fill a table, trace back) reappears in edit distance, sequence
alignment, and diff algorithms you will meet again outside this
course.
Recognizing "two sequences, compare them, order matters, gaps
allowed" as an LCS-shaped problem on sight is the actual
transferable skill.
Preview: One More Dimension of Choice
Not required this week - a look at where 2-D DP goes next.
CLRS's next dynamic-programming problem, matrix-chain
multiplication (§14.2), asks: given a chain of matrices to multiply
together, in what order should you group the multiplications
(parenthesize them) to do the fewest total scalar multiplications?
Define = the minimum cost to multiply the chain from matrix through matrix , and split it at every possible point :
LCS's recurrence only ever looks at three fixed neighbors - never
anywhere else in the table. Matrix-chain's recurrence must try every split point between and before taking the
minimum, an extra inner loop at every single cell - here so the shape
looks familiar the moment it appears later in CLRS §14.2.
What Two-Sequence DP Still Cannot Do
CampusNav can now optimize over one sequence (Week 11) and compare
two sequences side by side (Week 12) - but every table we've built
this whole course runs down arrays or strings: one line of data, or
two lines laid next to each other. CampusNav's biggest remaining
feature, actual walking directions across the real campus, isn't a
line at all - it's buildings and paths that branch, loop back, and
connect in many different ways at once. Nothing we have built
represents that yet.
Next Week
Week 12 leaves no way to represent a network of connected
places unsolved. Week 13, Graph Representation, addresses it:
modeling CampusNav's buildings and walkways as nodes and edges for
the first time.
Where This Week Lives in CLRS
One table, mapping today's topic to its exact source.
This week's topic
CLRS 4th ed
Longest common subsequence, the full derivation, recurrence, and traceback
Ch 14, §14.4
If you want to go deeper (not required this week):
§14.2, matrix-chain multiplication - the "one more dimension of
choice" preview from a few slides ago, worked out in full; §14.5,
optimal binary search trees - a third DP problem shaped like LCS's
2-D table, applied to search-tree layout instead of sequence matching.
Summary
A subsequence allows gaps; a substring does not - LCS is
built entirely on the former, never the latter.
The recurrence: matching characters extend the diagonal by 1;
mismatched characters take the better of dropping either character.
Traceback reconstructs the actual LCS string, not just its
length - walk backward from the table's corner, and a genuine tie
means more than one correct answer exists.
Complexity: O(mn) time and space (O(min(m,n)) space if only
the length is needed).
New: Week 12 Check - a short graded exercise on today's LCS
technique, released now, due before Week 13 begins, separate from
Assignment 3 (Greedy & Divide-and-Conquer, released Week 10, due
this week) - see materials/assignments/week12-check.html.
Summary, Continued
Reading: CLRS, Chapter 14 (Dynamic Programming), §14.4
Longest Common Subsequence.
Prepare: think about how you'd represent CampusNav's buildings
and the walkways connecting them as data. Bring one idea to Week 13.
Reminder: Assignment 3 (Greedy & Divide-and-Conquer) is due
this week - submit via the course Learning Management System (LMS).
Thank You
SLOT 1: Title
notes: Open by naming the algorithm behind `git diff`, which decides what changed between two versions of a file line by line. Say: "By the end of today, you'll know the exact algorithm behind that - and it's the same one CampusNav uses to match study buddies."
SLOT 2: Where we are
notes: Point at Wk 12. Say: "Last week DP solved one sequence at a time. Today it learns to compare two."
SLOT 3: Recap + open wound
SLOT 4: The pain (Act 1 / MOTIVATE), zero jargon
notes: Do not say "subsequence" or "LCS" yet. Let the class feel that both naive checks fail for a reason they can't yet name.
SLOT 5: Cost of not knowing
SLOT 6: Driving question
SLOT 7: Learning outcomes
Key Words Today, session 1 (kept after Act 1 / MOTIVATE per SPINE.md's no-definition-before-slot-8 rule)
notes: Read each term aloud once. Say: "Watch that third one closely - today's whole topic hinges on the difference between rows two and three."
SLOT 8: Origin
SLOT 9: Core concept
Key Words Today, session 2
notes: Read each term aloud. Say: "These four words are what every DP week, including last week, has secretly been built from."
Act 3 / BUILD
Idea + pseudocode: memoization vs. tabulation for LCS
Dense worked example, LCS, simple tier
Dense worked example, LCS, moderate tier (full DP table, too large for a card - shown full-width)
Dense worked example, LCS, moderate tier, continued: how two of its cells were filled
Dense worked example, LCS, harder tier (traceback + tie handling)
SLOT N-2: Worked example
SLOT N-1: Common mistakes
Key Words Today, session 3
notes: Read each term aloud. Say: "Edit distance is the same idea, one small step further - CLRS covers it right after LCS if you want to go deeper."