Spelling Test Fixes

Harddynamic programmingAlso known as Edit Distance (Levenshtein Distance)

A primary-school teacher scores each word on a spelling test by "fixes": the smallest number of single-letter fixes that turn the child's attempt into the correct word. A fix adds one letter, removes one letter, or changes one letter into another.

She wants a program to work out the score.

Your task

Write fewestFixes(attempt, word). Return the smallest number of fixes that turn attempt into word, where each fix inserts one letter anywhere, deletes one letter, or replaces one letter with a different letter.

If the strings are equal, return 0. Either string may be empty.

fewestFixes(attempt: string, word: string) → int

Examples

Example 1
Input
attempt = "recieve"
word = "receive"
Output
2
Why

Change the i to e and the e after it to i: 2 fixes. There is no 1-fix answer, because the strings differ in two positions and have the same length, so one insert or delete cannot help.

Example 2
Input
attempt = "nite"
word = "night"
Output
3
Why

Keep the n, the i and the t. Add a g and an h before the t, then remove the final e. That is 3 fixes, and no shorter list of fixes works.

Constraints

  • 0 ≤ attempt.length, word.length ≤ 500
  • Both strings contain only lowercase letters a to z.
Start with brute force

Run a breadth-first search over every string reachable in 1 fix, then in 2 fixes, and so on. Each string has hundreds of neighbours, so after a few levels there are billions of strings.

A recursive last-letter rule is smaller but still exponential, because it reaches the same pair of prefixes along many paths. For 500-letter strings you need a table.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code