Show problems as
Classic problem #72MediumStringDynamic Programming

Edit Distance

Real-world version: Command Correction Cost
Tracked in this browser only
Read Edit Distance on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstOptimal Substructure · Dynamic Programming, animated step by step

A shell offers a suggestion whenever a command is mistyped, and it ranks candidate suggestions by how much repair work each one needs.

You are given the string typed, which is what the user entered, and the string intended, which is the candidate command. A repair is exactly one of these three keystroke-level operations:

  • drop one character from anywhere in the current text
  • add one character at any position in the current text
  • overwrite one character of the current text with a different one

Return the least number of repairs that turns typed into intended. Either string may be empty, and both are made of lowercase letters.

Examples

Example 1

Input
typed = "grep", intended = "grape"
Output
2

Overwrite the third character with a and add e at the tail; no single repair can close the gap.

Example 2

Input
typed = "flaot", intended = "float"
Output
2

The two transposed characters each need an overwrite, since swapping a pair is not one of the allowed repairs.

Example 3

Input
typed = "", intended = "cat"
Output
3

Starting from nothing, every character of the candidate has to be added.

Constraints

  • 0 <= typed.length <= 500
  • 0 <= intended.length <= 500
  • typed and intended contain only lowercase English letters

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def correction_cost(typed: str, intended: str) -> int:
Java
public int correctionCost(String typed, String intended)