Skip to the code
cf.
+50 XP

#540 Typo Distance With Swaps

hard

Fast typists often swap two neighboring letters, like teh for the. A search box wants a typo distance that counts such a swap as a single edit. The allowed edits are: insert a character, delete a character, replace a character, or swap two neighboring characters.

There is one restriction: once two characters have been swapped, neither of them may be edited again, and nothing may be inserted between them. Write typoDistance(a, b) that returns the fewest edits that turn a into b under these rules.

Example 1

Input: a = "teh", b = "the"
Output: 1

Swap e and h.

Example 2

Input: a = "recieve", b = "receive"
Output: 1

Swap i and e. Plain edit distance would count 2 replacements.

Constraints

  • 0 <= a.length, b.length <= 500
  • Both contain only lowercase English letters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).