Algorithms · Working together

The diff algorithm

How GitHub knows exactly which lines you changed. Finding the smallest set of edits between two files is a classic puzzle with a beautiful answer.

The problem

You open a pull request. GitHub shows a wall of grey, a few green lines for additions and a few red ones for deletions. You added one line near the top of a file, but the page doesn't claim you rewrote the whole thing. It points at just the lines that changed.

A computer has no idea what you meant. It gets two blobs of text, before and after, and must work out the smallest set of edits that turns one into the other. That list of edits is what we call a diff.

The obvious way

Compare line 1 to line 1, line 2 to line 2, and so on, flagging every mismatch. It works until someone inserts one line near the top. Now every old line sits one position lower than it used to, so every position mismatches, and the diff reports a total rewrite even though almost nothing changed.

The clever idea

Think of two people reading the same poem from different printings. Instead of matching page numbers, they hunt for the lines both versions share, in the same order, and tick them off. Whatever isn't ticked in the old copy was deleted, and whatever isn't ticked in the new copy was added.

The biggest set of lines you can tick off is called the longest common subsequence. Finding it is the same problem as finding the fewest edits, and Eugene Myers' 1986 paper "An O(ND) Difference Algorithm" is the approach behind Git's default diff.

How the code does it

The naive version, the first function, only ever asks "are these two lines equal at this index?". After the inserted "a poem:" line, every comparison is off by one, so it flags six changed lines.

The clever version first fills a table. Cell t[i][j] holds how many lines the old text from i onward shares with the new text from j onward. The walk then follows the table from the top corner: matching lines are kept, and at a mismatch it takes whichever step keeps the shared count highest. The result is four changed lines: one added, two removed, one added back as the edit.

Trade-offs

This table has one cell per pair of lines, so its work and memory grow with the product of the two lengths. That's fine for a poem and wasteful for huge files. Myers' O(ND) algorithm is built around D, the number of differences, so it is fast when files are similar. Git also offers patience and histogram diffs, which can read better in some cases.

Where else you'll see it

The same idea powers git diff in your terminal, merge tools that compare versions, and any "track changes" view that highlights what moved between two drafts.

All lines are distinct. You insert one new line at the very top of a 4-line file and change nothing else. What does the naive position-by-position diff report?

  • Just 1 added line
  • Every position mismatches, so it flags nearly everything
  • No changes at all
Show the answer

Every position mismatches, so it flags nearly everything. Each old line now sits one index lower, so no position matches. An LCS-based diff would see all 4 old lines as shared and report just 1 addition.

Change it and see
  • Delete "a poem:" from new and rerun
  • Change "sugar is sweet" to match a new line
  • Make old and new identical

The code

Python, with what each line means beside it. It compares the clever way with comparing line 1 to line 1, line 2 to line 2.

old = ["roses are red", "violets are blue", "sugar is sweet", "and so are you"]Save the old poem as a list of lines
new = ["a poem:", "roses are red", "violets are purple", "and so are you"]Save the new poem, with edits
def naive(a, b):Naive diff: compare lines by position
out = []Start with an empty result
for i in range(max(len(a), len(b))):Walk through every position in either poem
x = a[i] if i < len(a) else NoneGrab the old line here, if any
y = b[i] if i < len(b) else NoneGrab the new line here, if any
if x == y:If the two lines match
out.append(" " + x)Keep it, unmarked
else:Otherwise
if x: out.append("- " + x)Mark the old line as removed
if y: out.append("+ " + y)Mark the new line as added
return outHand back the result
def lcs_table(a, b):Build a table of shared-line counts
t = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]Make a grid of zeros, one extra row and column
for i in range(len(a) - 1, -1, -1):Go through old lines, last to first
for j in range(len(b) - 1, -1, -1):Go through new lines, last to first
if a[i] == b[j]:If these two lines match
t[i][j] = 1 + t[i + 1][j + 1]Extend the best match from the rest by one
else:Otherwise
t[i][j] = max(t[i + 1][j], t[i][j + 1])Take the better of skipping either line
return tReturn the finished table
def smart(a, b):Smart diff: walk the table
t = lcs_table(a, b)Build the table first
i, j, out = 0, 0, []Start at both tops, with an empty result
while i < len(a) or j < len(b):Repeat until both poems are used up
if i < len(a) and j < len(b) and a[i] == b[j]:If both current lines match
out.append(" " + a[i])Keep the line, unmarked
i += 1Step forward in the old poem
j += 1Step forward in the new poem
elif i < len(a) and (j == len(b) or t[i + 1][j] >= t[i][j + 1]):Else if dropping the old line costs nothing
out.append("- " + a[i])Mark the old line as removed
i += 1Step forward in the old poem
else:Otherwise
out.append("+ " + b[j])Mark the new line as added
j += 1Step forward in the new poem
return outHand back the diff
show(lcs_table(old, new), "LCS table: old lines down, new across")Draw the table as a grid
results = {"naive": naive(old, new), "smart": smart(old, new)}Run both diffs and keep the results
for name, diff in results.items():For each method
print(name, "diff:\n" + "\n".join(diff))Print its diff, one line per row
show({n: sum(l[0] != " " for l in d) for n, d in results.items()}, "changed lines")Chart how many lines each marks changed

Read more

Run it. Then change it.

The code runs right in the page and draws as it goes. Free, nothing to install.

More on working together