Browse Curriculum

Edit Distance

Calculate the minimum number of operations (insert, delete, replace) required to convert one string into another.

Ø
R
O
S

Ready

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Intuition

Think of it as the "cost" to transform one word into another. If characters match, it costs nothing. If they differ, you pay a price for an operation (Insert, Delete, or Replace). We want to find the cheapest path involves checking all three possibilities at each step.

Concept

2D Dynamic Programming:

We define `dp[i][j]` as the edit distance between the first `i` characters of word1 and the first `j` characters of word2.

Recurrence Relation:

  • Match (word1[i] == word2[j]): `dp[i-1][j-1]` (No op needed).
  • Mismatch (word1[i] != word2[j]): `1 + min(Insert, Delete, Replace)`
    • Insert: `dp[i][j-1]`
    • Delete: `dp[i-1][j]`
    • Replace: `dp[i-1][j-1]`

How it Works

Tabulation Algorithm:

  1. Initialize `dp` table of size (m+1) \times (n+1).
  2. Base Cases: First row (transform to empty string) = `j`. First column (transform from empty string) = `i`.
  3. Iterate i from 1 to m, j from 1 to n.
  4. Apply recurrence relation.
  5. Result is `dp[m][n]`.

Step-by-Step Breakdown

Visualizing the Table:

  • Diagonal Move (No Cost): Match found.
  • Diagonal Move (Cost 1): Replacement.
  • Left Move (Cost 1): Insertion.
  • Up Move (Cost 1): Deletion.

When to Use

Applications:

  • Spell checkers (Levenshtein distance).
  • DNA sequence alignment (mutation analysis).
  • Plagiarism detection.

When NOT to Use

  • Simple Matches: If only exact matches matter.
  • Restricted Ops: If only insertions/deletions allowed, it's simpler (related to LCS).

How to Identify

"Minimum operations to convert...", "Levenshtein distance".

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep