Edit distance

Dynamic Programming DP on strings Hard
  • One practical real-world application of this problem is in spell-checking and auto-correction algorithms in text editing software and various applications like Google Docs, MS Word, or even your smartphone's keyboard
  • The underlying concept is known as Levenshtein distance, which defines the minimum number of single-character edits required to change one word into another
  • The fewer the changes required, the higher the probability that the words are similar or related, which can be used to suggest corrections or alterations for misspelled words or for predictive text functionality

Given two strings start and target, you need to determine the minimum number of operations required to convert the string start into the string target. The operations you can use are:


Insert a character: Add any single character at any position in the string.

Delete a character: Remove any single character from the string.

Replace a character: Change any single character in the string to another character.


The goal is to transform start into target using the fewest number of these operations.

Examples:

Input: start = "planet", target = "plan"

Output: 2

Explanation: 

To transform "planet" into "plan", the following operations are required:

1. Delete the character 'e': "planet" -> "plan"

2. Delete the character 't': "plan" -> "plan"

Thus, a total of 2 operations are needed.

Input: start = "abcdefg", target = "azced"

Output: 4

Explanation: 

To transform "abcdefg" into "azced", the following operations are required:

1. Replace 'b' with 'z': "abcdefg" -> "azcdefg"

2. Delete 'd': "azcdefg" -> "azcefg"

3. Delete 'f': "azcefg" -> "azceg"

4. Replace 'g' with 'd': "azceg" -> "azced"

Thus, a total of 4 operations are needed.

Input: start = "saturday", target = "sunday"

Constraints

  • 1 ≤ start.length, target.length ≤ 1000

Hints

  • Define dp[i][j] as the minimum number of operations required to convert start[0:i] into target[0:j].
  • If start[i-1] == target[j-1], no operation is needed dp[i][j]=dp[i−1][j−1]. Otherwise, we can insert, delete and replace.

Company Tags

Freshworks Databricks Texas Instruments Swiggy American Express Siemens Healthineers Etsy Shopify Dropbox Deloitte PwC Salesforce Snowflake Unity Technologies Walmart Nutanix Optum Qualcomm Cloudflare Johnson & Johnson Epic Systems IBM McKinsey & Company Bloomberg PayPal Google Microsoft Amazon Meta Apple Netflix Adobe