Sub topic 13
From LCS to Diff Output
This chapter assumes you can build the LCS table bottom-up, trace back through it, and use the identity from the previous chapter: with only insertions and deletions allowed, the minimum number of edits is m + n − 2 · LCS. Here we turn that identity into the line-by-line output you see from diff and git diff.
Lines as Sequence Elements
A diff tool runs LCS on lists of lines, not on characters. Each whole line counts as one element, and two lines match only if they are exactly equal. The LCS of the two files is the largest set of lines that can stay where they are. Every other line in the old file is a deletion, and every other line in the new file is an insertion.
Building an Edit Script
The traceback in earlier chapters walked backward from the bottom-right cell, so its output came out reversed. For diff output it is easier to fill the table over suffixes. In this version, dp[i][j] is the LCS length of a[i:] and b[j:]. You can then walk forward from (0, 0) and print lines in file order.
def diff_lines(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
if a[i] == b[j]:
dp[i][j] = dp[i + 1][j + 1] + 1
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j + 1])
out = []
i = j = 0
while i < m and j < n:
if a[i] == b[j]:
out.append(" " + a[i])
i += 1
j += 1
elif dp[i + 1][j] >= dp[i][j + 1]:
out.append("- " + a[i])
i += 1
else:
out.append("+ " + b[j])
j += 1
out.extend("- " + line for line in a[i:])
out.extend("+ " + line for line in b[j:])
return out
old = ["import os", "def main():", " print('hi')", " return 0"]
new = ["import os", "import sys", "def main():", " print('hello')", " return 0"]
print("\n".join(diff_lines(old, new)))Output:
import os
+ import sys
def main():
- print('hi')
+ print('hello')
return 0The LCS has 3 lines, so the script contains 4 + 5 − 2 · 3 = 3 edits: one deletion and two insertions. A changed line shows up as a deletion followed by an insertion, because LCS has no substitution operation.
What Real Tools Add
| Concern | Textbook LCS | Production diff |
|---|---|---|
| Line comparison | String equality | Lines hashed to integers first |
| Algorithm | O(mn) table | Myers' O((m+n)·D) algorithm, where D is the edit count |
| Output | Every line | Hunks with a few lines of context (unified format) |
| Readability | Any minimal script | Heuristics such as patience or histogram diff |
GNU diff and Git's default both use Myers' algorithm. It finds a minimal edit script, so its edit count equals m + n − 2 · LCS, and it runs fast when the files differ in only a few places. Patience and histogram diff anchor on lines that appear only once in each file. Their output often lines up better with code structure, but the edit script is not always minimal.
Exercise
Run diff_lines on old = ["a", "b", "c"] and new = ["c", "b", "a"]. How many lines does the LCS have, how many edits does the script contain, and why is the output not unique?
Show answer
The LCS has 1 line, so the script contains 3 + 3 − 2 · 1 = 4 edits. The lines "a", "b", and "c" each form a valid LCS on their own. The tie-break picks one: with >=, the walk deletes "a" and "b", keeps "c", then inserts "b" and "a". A different tie-break could keep "a" or "b" and still use 4 edits.
Exercise
Why does a one-character change inside a line appear as a deletion plus an insertion instead of a single edit?
Show answer
The diff treats each line as one sequence element. Two lines match only if they are fully equal, and LCS allows only insertions and deletions. The old line therefore has to be deleted and the new line inserted.