Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Edit distance

Edit distance (Levenshtein and variants) measures how many insertions, deletions, and substitutions turn one string into another; we use dynamic programming to compute it and apply it in spelling correction, DNA/protein sequence alignment, and OCR/post-processing.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Edit distance is used by engineers when comparing symbolic sequences. Examples: spell-checkers and auto-correct (choose the nearest dictionary word), OCR post-processing (fix recognition errors), DNA/protein sequence comparison (small-scale sequence alignment), and approximate string matching in search and data-cleaning. It gives a simple numeric measure of similarity for strings and sequences.

Key ideas

  • Edit distance (Levenshtein distance): the minimum total cost to transform one string into another using allowed edit operations. When all three operations have cost 1, this is the classical Levenshtein distance. Formally:

    • Given strings s (length m) and t (length n), the Levenshtein distance d(s,t) is the minimum number of insertions, deletions, and substitutions required to change s into t.
  • Assumptions: basic Levenshtein assumes that (1) operations are independent and can occur anywhere, (2) cost of insertion = deletion = substitution = 1 (unless stated otherwise), and (3) string positions are discrete and order matters.

  • Optimal substructure (dynamic programming): If the optimal transformation from s[1..i] to t[1..j] ends with

    • a deletion of s[i], then the first i-1 of s must have been transformed optimally to t[1..j];
    • an insertion of t[j], then s[1..i] was transformed optimally to t[1..j-1];
    • a substitution or match at the end, then s[1..i-1] to t[1..j-1] was optimal. This gives the recurrence used to build a DP table.
  • Recurrence (exact statement): Let d(i,j) be the minimum edit cost to change prefix s[1..i] into prefix t[1..j], with d(0,0)=0, d(i,0)=i (i deletions), d(0,j)=j (j insertions). For i>0 and j>0: d(i,j) = min( d(i-1,j) + cost(delete s[i]), d(i,j-1) + cost(insert t[j]), d(i-1,j-1) + cost(substitute s[i]→t[j]) ). For unit costs: cost(delete)=cost(insert)=1, cost(substitute)=0 if s[i]==t[j] else 1.

  • Damerau-Levenshtein distance: extends Levenshtein by allowing transposition (swap of two adjacent symbols) with its cost (often 1). It is useful when common errors are transpositions (e.g., typing "teh" instead of "the"). Note: the simple DP that just adds a neighboring-swap case computes the restricted form (also called Optimal String Alignment, OSA). The true Damerau–Levenshtein distance allows multiple transpositions and requires extra bookkeeping (last-seen indices) in the DP; both still run in O(m·n) time.

  • Complexity: The standard DP computes an (m+1)×(n+1) table in O(m·n) time and O(m·n) space. With technique to keep only two rows, space can be reduced to O(min(m,n)).

  • Diagram to draw (exam answers often require this): draw a matrix with rows i=0..m (source string s, include an initial empty row labelled i=0) and columns j=0..n (target string t, initial empty column j=0). Label row 0 across top with the characters of t preceded by an empty symbol; label column 0 down left with characters of s preceded by empty. Fill the top row with 0..n and first column with 0..m. Draw arrows into each cell (i,j) from (i-1,j), (i,j-1), (i-1,j-1) showing the three choices.

Formulas

d(0,0) = 0 — d(0,0) is the distance between two empty strings. Unit: unitless. Applies always.

d(i,0) = i for i ≥ 0 — delete all i characters to go from s[1..i] to empty. Unit: unitless. Applies when target prefix length is 0.

d(0,j) = j for j ≥ 0 — insert all j characters to go from empty to t[1..j]. Unit: unitless. Applies when source prefix length is 0.

d(i,j) = min(d(i-1,j) + 1, d(i,j-1) + 1, d(i-1,j-1) + δ) where δ = 0 if s[i] = t[j], else δ = 1. Unit: unitless. Applies for classical Levenshtein with unit costs.

Time complexity = O(m · n) — m = length of s, n = length of t. Unit: operations. Applies to standard DP.

Space complexity = O(m · n) (or O(min(m, n)) with optimized row reuse). Unit: table cells. Applies to implementations that keep full table or optimize memory.

For restricted Damerau–Levenshtein (Optimal String Alignment), one adds:

if i>1 and j>1 and s[i]=t[j-1] and s[i-1]=t[j] then consider d(i-2,j-2)+1 — extra candidate for transposition. Unit: unitless. Applies when adjacent transposition is allowed (restricted/OSA). For the full Damerau–Levenshtein distance (unrestricted), a different DP with last-occurrence bookkeeping is used; it also runs in O(m·n) time.

Worked examples

Example 1 (classical exam favorite): Compute Levenshtein distance between s = "kitten" (m = 6) and t = "sitting" (n = 7) with unit costs.

Step 1 — draw matrix of size 7×8 (rows i=0..6, columns j=0..7). Label top row with ['', s, i, t, t, i, n, g] and left column with ['', k, i, t, t, e, n].

Step 2 — initialise first row and column:

  • d(0,0)=0
  • first row j: 0 1 2 3 4 5 6 7
  • first column i: 0 1 2 3 4 5 6

Step 3 — fill table using recurrence. (Show key computed cells)

  • d(1,1): s[1]=k, t[1]=s → min(d(0,1)+1=2, d(1,0)+1=2, d(0,0)+1=1) = 1
  • Continue filling; common reference yields final d(6,7)=3.

You should draw the full table in the exam; the minimal sequence of edits is:

  • substitute k → s (1)
  • substitute e → i (1)
  • insert g at end (1) Total cost = 3. Final answer: 3 (unitless).

Example 2: s = "sunday" (length 6), t = "saturday" (length 8). Unit costs.

Step 1 — draw 7×9 matrix, initialise 0..8 and 0..6. Step 2 — fill using recurrence. The standard computation yields d = 3.

One possible minimal edit sequence:

  • insert 'a' after 's' (1)
  • insert 't' after 'sa' (1)
  • substitute 'n' → 'r' (1) Total cost = 3. Final answer: 3 (unitless).

(If you must show full numeric tables in an exam, write out each row; the exam markers expect the DP table with the final cell highlighted.)

Common mistakes

  • Forgetting to handle the base-case empty string.
  • Mixing up which string indexes rows vs columns — the visual table must match your recurrence indices.
  • Miscounting operations when reading back the edit sequence; the DP cell gives only the cost unless you backtrack carefully.
  • Assuming transposition is allowed in Levenshtein without explicitly using Damerau-Levenshtein.
  • Not optimising space: students sometimes claim O(min(m,n)) space but still write code that allocates full O(m·n) table.

For your exam

Types of questions you will see:

  • Definitions: define edit distance, Levenshtein distance, and Damerau-Levenshtein; be clear whether you mean the restricted (Optimal String Alignment) or the full Damerau–Levenshtein variant when transpositions are allowed.
  • Short notes: compare Levenshtein vs Damerau-Levenshtein; state time and space complexities; describe applications (spell-check, DNA, OCR).
  • Derivations: prove optimal substructure and derive the DP recurrence step-by-step.
  • Numericals: compute distance between two given short strings; draw/fill DP table and show backtracking to list edits.
  • Programs: write code or pseudo-code for the DP algorithm; explain space optimisation to two rows.
  • Diagrams: draw the DP matrix, label axes with string characters and initial conditions.

What full-marks answers include:

  • Clear definition with assumptions (operation costs, allowed operations).
  • Correct DP recurrence and boundary conditions written explicitly.
  • If numerical, a complete DP table with all values and a highlighted final cell; if requested, explicit backtracking to show edits.
  • Complexity analysis (time O(m·n), space O(m·n) or O(min(m,n))). If asked, state that the classical Levenshtein distance is a metric (non-negativity, identity of indiscernibles, symmetry, triangle inequality).
  • For Damerau variants, state the extra case for transposition and its condition.

Quick check

  1. Give the recurrence for Levenshtein distance d(i,j) with unit costs.
  2. What is the Levenshtein distance between "cat" and "cut"?
  3. What is the time complexity to compute distance between lengths m and n with standard DP?

Answers: 1) d(i,j)=min(d(i-1,j)+1, d(i,j-1)+1, d(i-1,j-1)+δ) where δ=0 if s[i]=t[j] else 1. 2) 1. 3) O(m·n).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?