Minimum insertions or deletions to convert string A to B

Dynamic Programming DP on strings Hard
  • One practical application of this problem in the software industry is in the realm of Version Control Systems like Git
  • When making changes to code, Git determines the differences (or 'diff') between two files
  • This involves determining the minimum number of changes that need to be made to transform one file into another, very similar to this problem
  • This function allows developers to easier identify, review, and understand changes made to the codebase

Given two strings str1 and str2, find the minimum number of insertions and deletions in string str1 required to transform str1 into str2.


Insertion and deletion of characters can take place at any position in the string.

Examples:

Input: str1 = "kitten", str2 = "sitting"

Output: 5

Explanation: To transform "kitten" to "sitting", delete "k" and insert "s" to get "sitten", then insert "i" to get "sittin", and insert "g" at the end to get "sitting".

Input: str1 = "flaw", str2 = "lawn"

Output: 2

Explanation: To transform "flaw" to "lawn", delete "f" and insert "n" at the end. Hence minimum number of operations required is 2".

Input: str1 = "abcdef", str2 = "ghijkl"

Constraints

  • 1 ≤ str1.length, str2.length ≤ 1000

Hints

  • "Instead of transforming str1 into str2 directly, find their Longest Common Subsequence (LCS). The LCS represents the common part that should remain unchanged. The rest of the characters in str1 must be deleted, and the missing characters from str2 must be inserted."
  • "Min Deletions=len(str1)−LCS(str1,str2) Min Insertions=len(str2)−LCS(str1,str2) Total Operations=Min Insertions+Min Deletions"

Company Tags

Bloomberg PwC Nutanix Docker Salesforce Snowflake Pinterest Micron Technology Databricks HCL Technologies Byju's Lyft NVIDIA Rockstar Games Splunk KPMG AMD Western Digital Epic Systems Wayfair Flipkart Visa Deloitte Unity Technologies Target Google Microsoft Amazon Meta Apple Netflix Adobe