Edit distance
A spell checker can rank its suggestions by how far each dictionary word is from what you typed. Here distance is counted in edits, and each edit changes one letter in one of three ways:
- insert one letter anywhere,
- delete one letter,
- replace one letter with a different letter.
You get two strings, source and target. Return the smallest number of edits that changes source into target. Every edit costs 1, and a string is 0 edits away from itself.
source = "cat", target = "act"Output2Delete the c to get "at", then insert a c after the a to get "act". Replacing the first two letters also takes 2.
source = "bread", target = "beard"Output2Delete the r to get "bead", then insert an r after the a to get "beard". Replacing the three middle letters also works, but costs 3.
source = "rain", target = "shine"Output3Replace the r with s and the a with h, keep the i and the n, then insert e at the end.
source = "", target = "map"Output3An empty source needs one insert per letter.
0 ≤ len(source), len(target) ≤ 500
Both strings use only lowercase English letters.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.