Say we are editing a string A of length m into a string B of length n using a minimal edit sequence.
A key fact to notice is that in a minimal edit sequence, each of the characters in A and B is operated on at most once. (This is easy to show; if a character is operated on twice, we can combine those operations into a single equivalent operation.)
It follows that we can partition the characters in A and B as:
- Characters in
A that are deleted (and are not in B)
- Characters in
B that are inserted (and are not in A)
- Pairs of a character from
A and a character from B which are either:
- Substituted (and are therefore different)
- Left alone (and are therefore the same)
Consider A[m] and B[n], the last characters of A and B. The following are possible cases for the minimal edit sequence; we claim that at least one of them is true:
A[m] is deleted
B[n] is inserted
A[m] is paired with B[n]
If 1) is false, then A[m] must be paired with a character A[m]' in B,
and if 2) is also false, then B[n] must be paired with a character B[n]' in A.
Note that all edit operations preserve the order of the characters.
So we cannot have A[m]' before B[n] and B[n]' before A[m] -- otherwise the pairs have changed order.
Thus, A[m]' is B[n] and B[n]' is A[m] -- that is, A[m] is paired with B[n], and the claim is demonstrated.
What remains is simple recursion on each of the three possible cases.
Let A[..m-1] represent all of A except its last character A[m], and B[..n-1] represent all of B except its last character B[n].
In case 1), to edit A into B we must delete A[m] and edit A[..m-1] into B,
which in total can be done in a minimum of 1 + distance(A[..m-1], B) operations.
In case 2), to edit A into B we must edit A into B[..n-1] and insert B[n],
which in total can be done in a minimum of 1 + distance(A, B[..n-1]) operations.
And in case 3), we must either substitute A[m] into B[n] if it has changed, or leave it alone if it has not, and then edit A[..m-1] into B[..n-1], which in total can be done in a minimum of 1 + distance(A[..m-1], B[..n-1]) operations
or distance(A[..m-1], B[..n-1]) operations respectively.
As these are the only possible cases, choosing a case for which this minimum number of operations is smallest yields an edit sequence with the smallest possible number of operations.
I found these sources useful:
https://blog.cykerway.com/posts/2021/04/10/minimum-edit-distance.html
https://cstheory.stackexchange.com/questions/10391/proof-of-levenshtein-distance/48178#48178