Myers diff algorithm
The conceptHow git diff knows exactly which lines you changed
A diff tool compares an old file and a new file and lists the fewest lines to delete and insert to turn one into the other. Eugene Myers's 1986 algorithm finds such a shortest list quickly.
The key is the longest common subsequence: the longest list of lines found in both files in the same order, not always adjacent. Those lines are kept; every other old line is deleted and every other new line inserted.
Example: old lines A B C A B B A and new lines C B A B A C share C A B A in order, four lines. So the shortest diff deletes 3 lines and inserts 2.
What it’s forGives the size of the shortest diff between two files.
D = N + M − 2·L
- N
- number of lines in the old file
- M
- number of lines in the new file
- L
- length of the longest common subsequence, the lines kept
- D
- fewest lines deleted plus inserted
What it givesThe minimum number of − and + lines a diff must show.
- Old file 7 lines, new file 6 lines, 4 lines shared in order
- D = 7 + 6 − 2·4 = 13 − 8 = 5
- So 3 deletions and 2 insertions