Spelling Test Fixes

Harddynamic programmingAlso known as Edit Distance (Levenshtein Distance)

A primary-school teacher marks weekly spelling tests. Instead of a plain right or wrong, she gives each word a "fixes" score: the smallest number of single-letter fixes that turn the child's attempt into the correct word. A fix is adding one letter, removing one letter, or changing one letter into another.

A score of 1 means "so close", and a big score means "let's practise this one". Marking thirty tests by hand is slow, so 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 two strings are already 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 n, i and t. Add g and h before the t, then remove the final e: n, i, +g, +h, t, -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

Explore every sequence of fixes, for example with breadth-first search over all strings reachable in 1 fix, then 2, and so on. Each string has hundreds of neighbours (26 letters to insert at each gap, plus deletes and replaces), so after a few levels there are billions of strings.

A recursive version of the last-letter rule is much smaller but still exponential, because it reaches the same pair of prefixes along many different paths. With 500-letter strings that is hopeless without 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