Week 12: Dynamic Programming II

Computer Algorithms (506994-002)

Ridho Hendra, Ph.D · Dept. of Intelligent Computing · Mon [1-3] · Building A, Room 703
Department of Intelligent Computing

Where We Are

Wk 1
Introduction
Wk 2
Algorithm Concepts
Wk 3
Complexity Analysis
Wk 4
Recursion & Recurrence
Wk 5
Basic Sorting
Wk 6
Advanced Sorting
Wk 7
Searching
Wk 8
Midterm Exam
Wk 9
Divide & Conquer
Wk 10
Greedy Algorithms
Wk 11
Dynamic Programming I
Wk 12
Dynamic Programming II
Wk 13
Graph Representation
Wk 14
Shortest Path
Wk 15
Final Exam
Department of Intelligent Computing

Last Week, This Week

  • Last week delivered: Week 11 solved 1-D optimization problems with dynamic programming - the Tour Planner (a knapsack-shaped problem) and the climbing-stairs counter - by breaking one sequence of choices into overlapping subproblems along a single table.
  • Last week left broken: CampusNav's next feature doesn't optimize over one sequence - it needs to compare two different sequences against each other. Week 11's 1-D table has nowhere to put a second sequence.
Department of Intelligent Computing

CampusNav Can't Find Study Buddies

Minji and Junho both use CampusNav. Each has a weekly class list, in
order: Monday's first class, then the next, and so on. CampusNav
wants to tell them "you two have a lot of classes in common - study
together!" First it tries: are their two lists exactly the same,
in the same order? Almost never true, so it says "no match" for
nearly everyone. Then it tries: do they have a run of
back-to-back identical classes? Still almost nothing - Minji and
Junho actually share four classes, just scattered across different
days and periods. CampusNav tells them they have nothing in common.
It's wrong.

Department of Intelligent Computing

How Many Matches Are We Missing?

"Exact same list" check
finds almost no pairs
"Back-to-back run" check
still misses most real overlap
Today's technique
finds the real shared courses
Illustrative, not measured data: the point is the gap, not the exact percentages.
Department of Intelligent Computing

What Else This Actually Costs

  • A "must be identical" check makes CampusNav's study-buddy feature suggest almost nobody - a feature that quietly does nothing.
  • A "must be a back-to-back block" check still misses most real students, because shared classes rarely land consecutively by coincidence.
  • Every wrong "no match" is a real student who never finds a study partner they actually had.
In industry: this exact comparison - find the longest matching stretch between two sequences, in order, gaps allowed - is what powers diff and Git's line-by-line change detection, spell-checkers, and DNA sequence alignment in bioinformatics. It is also one of the most frequently asked dynamic programming questions in technical interviews.
Department of Intelligent Computing

This Week's Question

"Given two sequences, how do we find the longest sequence of elements that appears in both - in the same relative order, but not necessarily touching - and reconstruct it, not just its length?"
Department of Intelligent Computing

By the End of This Week, You Can

  1. Distinguish a "subsequence" from a "substring," and explain why this problem needs the former.
  2. Derive the recurrence relation for the longest common subsequence (LCS) and justify both of its cases.
  3. Build a complete 2-D DP table for two sequences and use traceback to reconstruct the actual longest common subsequence.
  4. State and justify LCS's time and space complexity.
Department of Intelligent Computing

This Week, In the Three-Goals Table

A reminder from Week 1: this is still goal 2.
# Goal (from the syllabus) Where
1 Analyze correctness and efficiency precisely Weeks 2-3, 5, 7
2 Design algorithms with general paradigms (D&C, greedy, DP) Weeks 4, 9-12
3 Apply classic algorithms and reason about P vs. NP Weeks 5-7, 13-14

LCS is dynamic programming's second and final act this semester -
the paradigm applied to two sequences at once instead of one.

Department of Intelligent Computing

Key Words Today

  • Sequence: an ordered list of items - letters, course codes, anything where position matters.
  • Subsequence: a sequence built by deleting zero or more items from another, without reordering what's left.
  • Substring: a subsequence whose kept items are also contiguous - no deletions allowed in the middle.
  • Common subsequence: a sequence that is a subsequence of two (or more) different sequences at once.
Department of Intelligent Computing

This Problem Is Not New

You just felt the pain. Now: who else felt it, and what did they do?
  • 1970, bioinformatics: Needleman and Wunsch needed to compare
    two DNA or protein sequences for similarity - mutations insert,
    delete, and shift letters, so exact alignment almost never happens.
  • 1976, software tools: Hunt and McIlroy built the algorithm
    behind Unix diff - comparing two versions of a file line by line
    to report the minimal set of changes between them.
  • Both problems have the same shape: two sequences, find the
    longest stretch they share in order, without demanding they touch.
Department of Intelligent Computing

The Pattern Behind Both Fields

Bioinformatics and software tools, decades apart. Same underlying idea.
Neither field invented a new trick from scratch - both are solved by the same dynamic programming recurrence you'll derive today. A tool built to compare genetic mutations and a tool built to compare source code file revisions turn out to be the exact same algorithm underneath, wearing two entirely different names.
Department of Intelligent Computing

A Motivating Example: COMPUTER and COMMUTER

Two words. One idea, precisely, coming up next.

Two words: COMPUTER and COMMUTER. Without counting
letter-by-letter position, the longest run of letters that lines up,
in the same left-to-right order in both words, is not obviously "the
letters both words have" - some skipping is required to line it up.

Delete the P from COMPUTER and one M from COMMUTER, and both
become C-O-M-U-T-E-R - 7 letters, same relative order, in both
original words, even though those 7 letters are not all
next-to-each-other in either original word.

That's today's whole subject, precisely.

Department of Intelligent Computing

Subsequence & Common Subsequence: Definition

Fifty years of tools, and the COMPUTER/COMMUTER example, point at two words. Here they are, precisely.

A subsequence of a sequence is any sequence obtainable by
deleting zero or more elements from without changing the
relative order
of the remaining elements.

A common subsequence of and is a sequence that is a
subsequence of both. The longest common subsequence (LCS) is
the longest such sequence - its length, and the sequence itself.

Department of Intelligent Computing

Subsequence vs. Substring

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).
Department of Intelligent Computing

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.
Department of Intelligent Computing

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.

Department of Intelligent Computing

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).

Department of Intelligent Computing

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.

Department of Intelligent Computing

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.

Department of Intelligent Computing

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)
Department of Intelligent Computing

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.
Department of Intelligent Computing

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.

Department of Intelligent Computing
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.
Department of Intelligent Computing
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.
Department of Intelligent Computing
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.
→
2
Mismatches take the larger neighbor
L(4,1) (gold): X[4]=D, Y[1]=A, mismatch → max(L(3,1)=1, L(4,0)=0) = 1 - the up-neighbor wins.
→
3
Final answer
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.
Department of Intelligent Computing
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.
→
2
Traced on ALGDP/ALGRDP
(5,6)P→(4,5)D→(3,4) mismatch: L(2,4)=2 vs L(3,3)=3, detour left→(3,3)G→(2,2)L→(1,1)A. Reversed: A,L,G,D,P - 5 characters, matching L(5,6)=5 exactly.
→
3
A genuine tie elsewhere
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.
Department of Intelligent Computing

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.

Department of Intelligent Computing

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."

Department of Intelligent Computing

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.
Department of Intelligent Computing

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.
Department of Intelligent Computing

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.

Department of Intelligent Computing

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.

Department of Intelligent Computing

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.
Department of Intelligent Computing

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.

Department of Intelligent Computing

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.
Department of Intelligent Computing

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.

Department of Intelligent Computing

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.
Department of Intelligent Computing

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.
Department of Intelligent Computing

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).
Department of Intelligent Computing

Thank You

Department of Intelligent Computing

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."

Preview/outlook, clearly not required this week

SLOT N+1: Limits (Act 4 / CLOSE), becomes Week 13 slot 4

SLOT N+2: Bridge

Where This Week Lives in CLRS, positioned immediately before Summary

SLOT N+3: Summary

SLOT N+4: Thank You