Sub topic 13
From LCS to Diff Output
This chapter turns the LCS table into the output of a line-based diff tool. It assumes you have already worked through the bottom-up DP table, the traceback, and the result that insert/delete distance equals m + n - 2 * LCS. You should also be comfortable reading Python that works on lists of strings.
The Core Idea: Lines Are Symbols
A diff tool compares two versions of a file. It does not compare characters. It treats each line as one symbol, so a file becomes a list of strings, and two lines match only if they are exactly equal.
The LCS of the two line lists is the set of lines both versions share, in the same order. Every other line was either removed from the old file or added in the new one. As a result:
- Lines in the LCS are printed as unchanged context, with a leading space.
- Old lines outside the LCS are printed as deletions, with a leading
-. - New lines outside the LCS are printed as insertions, with a leading
+.
The number of - and + lines together is the insert/delete distance from the previous chapter. A longer LCS gives a shorter diff.
Emitting Edit Operations in File Order
The traceback from the earlier chapter starts at the bottom-right cell and walks backward, so it produces the answer in reverse. For a diff you want operations in file order. A simple fix is to build the table over suffixes instead of prefixes. dp[i][j] is then the LCS length of a[i:] and b[j:], and the walk starts at (0, 0) and moves forward.
def diff_ops(a, b):
m, n = len(a), len(b)
# dp[i][j] = LCS length of a[i:] and b[j:]
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])
ops = []
i = j = 0
while i < m and j < n:
if a[i] == b[j]:
ops.append((" ", a[i]))
i += 1
j += 1
elif dp[i + 1][j] >= dp[i][j + 1]:
ops.append(("-", a[i])) # prefer deleting first on ties
i += 1
else:
ops.append(("+", b[j]))
j += 1
while i < m:
ops.append(("-", a[i]))
i += 1
while j < n:
ops.append(("+", b[j]))
j += 1
return ops
old = """apple
banana
cherry
date
elderberry""".splitlines()
new = """apple
blueberry
cherry
date
fig
elderberry""".splitlines()
for tag, line in diff_ops(old, new):
print(tag + line)Output:
apple
-banana
+blueberry
cherry
date
+fig
elderberryThe LCS is apple, cherry, date, elderberry, with length 4. The diff has 1 deletion and 2 insertions, which matches 5 + 6 - 2 * 4 = 3.
Why the Tie Rule Matters
At the banana / blueberry step, both options give an LCS of 3 for the rest of the files. The >= comparison breaks the tie toward deletion, so -banana prints before +blueberry. If you flip it to >, you still get a valid diff of the same size, but the + line comes first. Most diff tools print deletions before insertions within a change, because readers find "old, then new" easier to follow. The ties chapter showed that the choice of LCS is arbitrary. In a diff, that choice changes what a person sees.
Grouping Changes into Hunks
Real diffs do not print the whole file. They print hunks, which are runs of changes surrounded by a few unchanged context lines. Each hunk has a header in the form @@ -old_start,old_count +new_start,new_count @@. If two changes are separated by no more than 2 * context unchanged lines, they go into the same hunk, because their context regions would otherwise overlap.
def unified_hunks(ops, context=3):
# Attach 1-based old/new line numbers to each operation.
rows = []
o = nw = 1
for tag, line in ops:
rows.append((tag, line, o, nw))
if tag != "+":
o += 1
if tag != "-":
nw += 1
changed = [k for k, r in enumerate(rows) if r[0] != " "]
if not changed:
return []
groups = []
start = end = changed[0]
for k in changed[1:]:
if k - end - 1 <= 2 * context: # unchanged gap small enough to merge
end = k
else:
groups.append((start, end))
start = end = k
groups.append((start, end))
out = []
for s, e in groups:
lo = max(0, s - context)
hi = min(len(rows), e + context + 1)
chunk = rows[lo:hi]
old_count = sum(1 for r in chunk if r[0] != "+")
new_count = sum(1 for r in chunk if r[0] != "-")
old_start, new_start = chunk[0][2], chunk[0][3]
# Unified diff convention: an empty range names the line before it.
if old_count == 0:
old_start -= 1
if new_count == 0:
new_start -= 1
out.append(f"@@ -{old_start},{old_count} +{new_start},{new_count} @@")
out.extend(tag + line for tag, line, _, _ in chunk)
return out
ops = diff_ops(old, new)
print("\n".join(unified_hunks(ops, context=0)))With context=0, the two changes are split into separate hunks:
@@ -2,1 +2,1 @@
-banana
+blueberry
@@ -4,0 +5,1 @@
+figThe second header says that zero old lines were replaced, after old line 4, and that one line now sits at new line 5. With context=1, the gap between the two changes is two unchanged lines (cherry, date). That is within 2 * 1, so everything merges into one hunk headed @@ -1,5 +1,6 @@.
Common Errors When Building a Diff
| Mistake | Symptom | Fix |
|---|---|---|
| Comparing characters instead of lines | Huge tables and unreadable output | Split with `splitlines()` and treat each line as one symbol |
| Mixing `\r\n` and `\n` line endings | Every line shows as changed | Normalize line endings before comparing |
| Missing newline at end of file | The last line differs from its twin | Track this flag separately, as `\ No newline at end of file` does |
| Prefix-based traceback without reversing | Diff prints bottom to top | Use a suffix table, or reverse the collected operations |
| Off-by-one in hunk headers | `patch` rejects the hunk | Use 1-based numbers and the "line before" rule for empty ranges |
How Production Tools Differ
The table-based approach costs O(mn) time and memory. Two 10,000-line files need 100 million cells, which is too much for an interactive tool. Production diff tools keep the same goal, a short insert/delete script, but get there faster:
- Trim common prefix and suffix first. Most edits touch a small part of a file, so removing the identical head and tail often shrinks the problem to a few lines.
- Hash lines to integers. Comparing integer IDs is cheaper than comparing long strings again and again inside the inner loop.
- Myers' algorithm. GNU diff and Git's default diff use Myers'
O((m + n) D)algorithm, whereDis the size of the edit script. It is fast when the files are similar, which is the usual case. It finds a shortest edit script, so it is still solving the LCS problem. - Patience and histogram diff. Git offers these heuristics. They anchor on lines that appear exactly once in each file, so they do not match common lines like blank lines or
}by accident. Their output can be longer than the minimum, but people often find it easier to read.
Python's difflib.unified_diff uses a different matching method (Ratcliff/Obershelp), not LCS. It can return a correct diff that is not the shortest one, so do not use it as an oracle when testing your LCS code.
Exercise
In diff_ops, change the tie condition from >= to >. Without running the code, what does the old/new example print, and is the edit script still minimal?
Show answer
Before the cherry line, the output becomes "+blueberry" followed by "-banana". The rest is unchanged. The script still has 3 changed lines, because both branches of a tie lead to an LCS of the same length. Only the order of the insertion and deletion changes.
Exercise
Two changed lines in the operation list are separated by 6 unchanged lines. With context=3, does unified_hunks put them in one hunk or two? What about with context=2?
Show answer
With context=3, the gap of 6 is at most 2 * 3 = 6, so the changes merge into one hunk. With context=2, 6 is more than 4, so you get two hunks, each with 2 lines of context on each side.
Exercise
An old file has 120 lines and a new file has 130 lines. Their line-level LCS has 110 lines. How many lines start with "-" and how many start with "+" in a full diff?
Show answer
Deletions are 120 - 110 = 10 and insertions are 130 - 110 = 20. That is 30 changed lines in total, which matches 120 + 130 - 2 * 110 = 30.