Min Operations to Convert Strings

Edit Distance Problem – Minimum Operations to Convert One String to Another

Problem Statement:

You are given two strings S1 and S2.

Your task is to convert S1 to S2 using the following allowed operations:

  1. Insert a character

  2. Delete a character

  3. Replace a character

Find the minimum number of operations required to make the transformation.

Example 1:

Input:

S1 = "horse", S2 = "ros"

Output:

3

Explanation:

Operations: replace 'h' → 'r', remove 'r', remove 'e'

Best Technique – Dynamic Programming

This is a classic 2D DP problem.
Let dp[i][j] represent the minimum edit distance between the first i characters of S1 and the first j characters of S2.

We build up the solution by comparing characters from both strings and checking for 3 possible operations: insert, delete, replace.

Different Approaches:

Approach 1: Brute Force (Recursion)

Try all possibilities recursively: insert, delete, or replace. This is slow and hits exponential time, but great for understanding the problem.

public class EditDistance { public static int editDistanceBrute(String s1, String s2) { return helper(s1, s2, s1.length(), s2.length()); } private static int helper(String s1, String s2, int i, int j) { if (i == 0) return j; if (j == 0) return i; if (s1.charAt(i - 1) == s2.charAt(j - 1)) { return helper(s1, s2, i - 1, j - 1); } return 1 + Math.min( helper(s1, s2, i - 1, j), // delete Math.min( helper(s1, s2, i, j - 1), // insert helper(s1, s2, i - 1, j - 1) // replace ) ); } public static void main(String[] args) { String s1 = "horse", s2 = "ros"; System.out.println("Edit Distance (Brute Force): " + editDistanceBrute(s1, s2)); } }

Approach 2: Dynamic Programming (Optimal)

This approach fills a DP table from bottom up, storing the results of all subproblems. Much faster and handles large strings efficiently.

public class EditDistance { public static int editDistance(String s1, String s2) { int m = s1.length(), n = s2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) dp[i][0] = i; for (int j = 0; j <= n; j++) dp[0][j] = j; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (s1.charAt(i - 1) == s2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = 1 + Math.min( dp[i - 1][j], // delete Math.min( dp[i][j - 1], // insert dp[i - 1][j - 1] // replace ) ); } } } return dp[m][n]; } public static void main(String[] args) { String s1 = "horse", s2 = "ros"; System.out.println("Edit Distance (DP): " + editDistance(s1, s2)); } }

⚠️ Common Pitfalls:

  • Off-by-one Errors: Remember string indices and lengths are different. Be careful with i - 1 and j - 1.

  • Base Cases: Setting up dp[0][*] and dp[*][0] properly is critical for correct results.

  • Recursive Time Bomb: Don’t use the brute force method on large inputs unless memoized — it explodes in time.

📊 Time and Space Complexity:

Approach     Time Complexity     Space Complexity
Brute Force           O(3^n)          O(n) (stack)
Dynamic Prog.           O(m * n)          O(m * n)

m = len(S1), n = len(S2)

🌍 Real-World Applications:

  • Spell Checkers: Suggest the closest dictionary word using edit distance.

  • Plagiarism Detection: Measure similarity between student submissions.

  • Bioinformatics: Compare DNA/RNA sequences with mutation tolerance.

  • Version Control Tools: Track file diffs using minimal edits between lines.


I hope you found this article insightful! Keep exploring, keep learning, and don’t forget to check back daily for more exciting problem breakdowns. If you know someone who would benefit from this, share it with them and help them grow too! That’s it for today—see you in the next post!

                                                                                                                                         Signing off!! 

                                                                                                Master DSA One Problem at a Time :)

Comments

Popular posts from this blog

Divisible Drama — Who’s In, Who’s Out?

Trailing Zeros in Factorial – How Many and Why?

Minimum equal sum