Proofs: LCS dynamic programming
These are the human proofs of LCS dynamic programming, at full length.
The LCS table holds the prefix LCS lengths and the traceback returns an LCS full
This proof shows: correctness.
We use the pseudocode of the page, with and . Write for the prefix of length and .
Lemma 1 (the fill). When LCS-LENGTH returns, for all and .
Proof. Order the cells by the time at which they get their final value: first the cells of lines L1 and L2, then the cells with in row-major order. No cell is written again after this time. We prove by induction along this order that each cell gets the value .
If or , the only common subsequence of and is the empty one, so , which lines L1 and L2 write.
Let . The cells and are in row (or in row 0 or column 0), and is earlier in row (or in column 0). So all three come before in the order, and by the induction hypothesis they hold , and . If , line L5 writes . If , lines L6 and L7 write : line L6 writes when it is at least , and line L7 writes otherwise. By the corollary of the optimal substructure theorem, the written value is in both cases.
Lemma 2 (the traceback). LCS-TRACEBACK stops, and returns a common subsequence of and of length .
Proof. Write for the suffix (empty if ), and the same for . We show this invariant of the loop of line L10:
(T) , , is a common subsequence of and , and .
Initialization. Line L9 sets , and empty. The suffixes are empty, the empty sequence is a common subsequence of them, and .
Maintenance. Assume (T) and .
- If (line L11), by Lemma 1 and the recurrence, . The new is a common subsequence of and : embed at index of and at index of , followed by the embeddings of , which use indices larger than and . And .
- If , by Lemma 1, . Line L12 moves to when , that is, when . Line L13 moves to otherwise, and then , so . In both cases the value of at the new cell is , so the equation stays true. does not change, and a common subsequence of and is also a common subsequence of the longer suffixes and , or and .
Termination. Each iteration lowers by at least 1, and the loop runs only while , so it stops after at most iterations.
At the end. The loop stops with or . Then by Lemma 1, so . By (T), is a common subsequence of and , which are suffixes of and , so it is a common subsequence of and .
Theorem. LCS-TRACEBACK(LCS-LENGTH, , ) returns a longest common subsequence of and .
Proof. By Lemma 2 the output is a common subsequence of length , which is the maximum length.