Boss lesson · Unit 03
Edit distance
Insert, delete or replace: three neighbours, one min
What you practise
- Insert, delete, replace
Try a question from this lesson
Pick one
dp[i][j] is the fewest edits that turn the first i letters of word a into the first j letters of word b. What is dp[3][0]?
Hint
The second prefix is empty here. What is the only kind of edit that helps?
Correct answer
3
Why
Turning three letters into nothing takes three deletions, whatever the letters are. So column 0 holds 0, 1, 2, 3, ... and, by the same argument with insertions, so does row 0. These are the base cases.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
How far apart are two words?
The edit distance between two words is the fewest single-letter edits that turn one into the other. Three edits are allowed: insert a letter, delete a letter, or replace a letter.
cat → cut is 1 edit (replace a with u). cat → cart is 1 edit (insert r). cat → dog is 3.
Spell checkers use it to suggest the closest real word to a typo.
Concept
Three neighbours, three edits
Compare the last letters of the two prefixes. If they are the same, nothing needs paying: copy the diagonal cell.
If they differ, pay 1 for the cheapest of three moves. Replace the letter: diagonal. Delete it from the first word: the cell above. Insert the needed letter: the cell to the left.
def cell(same, diag, up, left):
if same:
return diag
return 1 + min(diag, up, left)function cell(same, diag, up, left) {
if (same) return diag;
return 1 + Math.min(diag, up, left);
}function cell(
same: boolean,
diag: number,
up: number,
left: number,
): number {
if (same) return diag;
return 1 + Math.min(diag, up, left);
}Python notemin takes any number of arguments, so the three neighbours go in one call.
JavaScript noteMath.min also accepts any number of arguments: Math.min(diag, up, left).
9 more exercises in the app
- 3× type the answer
- 1× match the pairs
- 1× fill the blanks
- 3× multiple choice
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.