Edit distance
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Edit distance counts the fewest single-letter changes (add, delete or replace) needed to turn one word into another. A small number means the words are close. It powers the "did you mean" feature.
Practical use cases
- Web app: Did you mean this spelling in search. A shopper types "samsng" into a product search box and finds nothing. The app compares the typed word with its product names and finds "samsung" needs only one added letter. It then shows "Did you mean Samsung?" with results. The shop does not need an exact match, because the computer counts how few letter changes separate the typed word from each product name, and offers the closest one.
- Web app: Duplicate customer detection. A CRM wants to catch duplicate customers such as "Rajesh Kumar" and "Rajesh Kumr". Names within one or two edits of each other are shown to staff for merging, keeping the database clean. Staff then review a short list of pairs with one or two edits between them, which is quick work, instead of hunting through 50,000 customers by eye.
- System: Spell checkers and DNA matching. Spell checkers rank suggestions by how few edits they need. DNA tools measure how different two gene sequences are the same way. The number of edits also lets them rank suggestions, so the word needing one change appears above the word needing four.
The story: Mrs. Sharma's Spelling Fix
Mrs. Sharma was marking spelling tests. Kabir had written ROS when the word was HORSE. "How many small fixes would turn your word into the right one?" she asked. A fix could be inserting a letter, deleting a letter or replacing one letter. Kabir counted three. Was three the smallest possible?
Mira figured out that only the ends of the words matter. Look at the last letters. If they are the same, nothing needs fixing there: ignore them and fix the rest. If they differ, there are exactly three choices: replace one with the other (then fix both shorter words), delete the last letter of the first word, or insert the second word's last letter. Try all three, take the cheapest, and add one fix.
She wrote the answer for every pair of beginnings in a table. Each cell borrows from the diagonal (replace), the cell above (delete) and the cell to the left (insert). The corner showed 3. This is Edit Distance, also called Levenshtein distance, the idea behind your phone's "Did you mean...?" suggestions.
How to spot this problem, and where you need it
Users make typos or names differ slightly, and exact comparison says there is no match, even though a human can see they are nearly the same.
Signs you need it
- Search returns zero results for a query that is clearly a small misspelling of something that exists.
- You find duplicate records that differ by a letter, a missing space or a swapped character.
- The problem says "minimum number of operations to convert one string to another".
Where to use it in a project
- Did-you-mean suggestions in search boxes, autocomplete and "no results found" pages.
- Duplicate detection and data cleaning in customer, vendor or product lists.
The solution
Build a table with one row per letter of the first word and one column per letter of the second. The first row and column count 0, 1, 2 and so on, which is deleting or adding everything. For each other cell, if the letters match, copy the diagonal. Otherwise take 1 plus the smallest of the left cell (add), the cell above (delete), and the diagonal (replace). The bottom-right cell is the edit distance.
Payoff: Before: zero results for "samsng". After: "Did you mean Samsung?" because the distance is 1, found in a few thousand cell updates.
Explain it like I am 8
You have a Lego word and want it to look like another word. Each move is adding a block, taking one away or swapping one. You want the fewest moves. At each spot, if the blocks already match you move on for free; otherwise you try the three moves and pick the cheapest.
How it works, step by step
- Edge cases first: turning a word into an empty word costs its length; an empty word into a word costs that word's length.
- Compare the last letters of the two prefixes,
a[i-1]andb[j-1]. - If equal:
dp[i][j] = dp[i-1][j-1], no cost. - If different:
dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])(replace, delete, insert). - The bottom-right cell holds the minimum number of edits. Walking back shows which edits to make.
The code in four languages
PHP
<?php
// Smallest number of insert / delete / replace steps to turn $a into $b.
function editDistance(string $a, string $b): int {
$m = strlen($a); $n = strlen($b);
$dp = array_fill(0, $m + 1, array_fill(0, $n + 1, 0));
for ($i = 0; $i <= $m; $i++) $dp[$i][0] = $i; // delete every letter
for ($j = 0; $j <= $n; $j++) $dp[0][$j] = $j; // insert every letter
for ($i = 1; $i <= $m; $i++) {
for ($j = 1; $j <= $n; $j++) {
if ($a[$i - 1] === $b[$j - 1]) {
$dp[$i][$j] = $dp[$i - 1][$j - 1]; // same letter: free
} else {
$dp[$i][$j] = 1 + min(
$dp[$i - 1][$j - 1], // replace
$dp[$i - 1][$j], // delete from a
$dp[$i][$j - 1] // insert into a
);
}
}
}
return $dp[$m][$n];
}
echo editDistance('HORSE', 'ROS'), "\n"; // 3
echo editDistance('kitten', 'sitting'), "\n"; // 3JavaScript
// Smallest number of insert / delete / replace steps to turn a into b.
function editDistance(a, b) {
const m = a.length, n = b.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = 0; i <= m; i++) dp[i][0] = i; // delete every letter
for (let j = 0; j <= n; j++) dp[0][j] = j; // insert every letter
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (a[i - 1] === b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1]; // same letter: free
} else {
dp[i][j] = 1 + Math.min(
dp[i - 1][j - 1], // replace
dp[i - 1][j], // delete from a
dp[i][j - 1] // insert into a
);
}
}
}
return dp[m][n];
}
console.log(editDistance('HORSE', 'ROS')); // 3
console.log(editDistance('kitten', 'sitting')); // 3Java
public class Main {
// Smallest number of insert / delete / replace steps to turn a into b.
static int editDistance(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) dp[i][0] = i; // delete every letter
for (int j = 0; j <= n; j++) dp[0][j] = j; // insert every letter
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (a.charAt(i - 1) == b.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1]; // same letter: free
} else {
dp[i][j] = 1 + Math.min(
dp[i - 1][j - 1], // replace
Math.min(dp[i - 1][j], // delete from a
dp[i][j - 1])); // insert into a
}
}
}
return dp[m][n];
}
public static void main(String[] args) {
System.out.println(editDistance("HORSE", "ROS")); // 3
System.out.println(editDistance("kitten", "sitting")); // 3
}
}Go
package main
import "fmt"
// Smallest number of insert / delete / replace steps to turn a into b.
func editDistance(a, b string) int {
m, n := len(a), len(b)
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
dp[i][0] = i // delete every letter
}
for j := 0; j <= n; j++ {
dp[0][j] = j // insert every letter
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
if a[i-1] == b[j-1] {
dp[i][j] = dp[i-1][j-1] // same letter: free
} else {
dp[i][j] = 1 + min(
dp[i-1][j-1], // replace
dp[i-1][j], // delete from a
dp[i][j-1], // insert into a
)
}
}
}
return dp[m][n]
}
func main() {
fmt.Println(editDistance("HORSE", "ROS")) // 3
fmt.Println(editDistance("kitten", "sitting")) // 3
}Time: O(m × n) · Extra space: O(m × n), or O(n) if only the number is needed. Brute force tries three options at every letter, which explodes; the table solves each pair of prefixes once.
Watch out for
- Forgetting to fill the first row and column (0, 1, 2, 3...). Without them the table has nothing to start from.
- Adding 1 even when the letters match. Matching letters cost nothing.
- Mixing which neighbour means which edit. Diagonal = replace, up = delete, left = insert.
Quick check
- Which neighbour represents "replace one letter"?
- Above
- Left
- Diagonal
- Edit distance from "" (empty) to "ROS"?
- 0
- 3
- 1
- When the last letters match, the cost is...
- Same as the diagonal cell
- 1 plus the diagonal
- Always 0