levenshtein

levenshtein(string $string1, string $string2, int $insertion_cost = 1, int $replacement_cost = 1, int $deletion_cost = 1): int

Computes the Levenshtein edit distance between two strings: the minimum number of single-character insertions, deletions or substitutions.

C C23

C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Hand-written classic DP (nothing built in): a two-row rolling array, O(len_a*len_b) */
static int levenshtein(const char *a, const char *b) {
    size_t la = strlen(a), lb = strlen(b);
    int *prev = malloc((lb + 1) * sizeof(int));
    int *cur = malloc((lb + 1) * sizeof(int));
    for (size_t j = 0; j <= lb; j++) prev[j] = (int)j;
    for (size_t i = 1; i <= la; i++) {
        cur[0] = (int)i;
        for (size_t j = 1; j <= lb; j++) {
            int cost = a[i - 1] == b[j - 1] ? 0 : 1;
            int m = prev[j] + 1;            /* Deletion */
            if (cur[j - 1] + 1 < m) m = cur[j - 1] + 1;  /* Insertion */
            if (prev[j - 1] + cost < m) m = prev[j - 1] + cost; /* Substitution/match */
            cur[j] = m;
        }
        int *tmp = prev; prev = cur; cur = tmp; /* Rolling reuse */
    }
    int result = prev[lb];
    free(prev);
    free(cur);
    return result;
}

int main(void) {
    printf("%d\n", levenshtein("kitten", "sitting")); /* 3: the textbook case */
    printf("%d\n", levenshtein("flaw", "lawn"));      /* 2 */
    printf("%d\n", levenshtein("", "abc"));           /* 3: all insertions */
    printf("%d\n", levenshtein("abc", "abc"));        /* 0: identical means 0 */
    return 0;
}
Output
3
2
3
0

C++ C++26

C++26
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

// Hand-written classic DP (nothing built in): a two-row rolling array
static int levenshtein(const std::string &a, const std::string &b) {
    std::vector<int> prev(b.size() + 1), cur(b.size() + 1);
    for (size_t j = 0; j <= b.size(); j++) prev[j] = static_cast<int>(j);
    for (size_t i = 1; i <= a.size(); i++) {
        cur[0] = static_cast<int>(i);
        for (size_t j = 1; j <= b.size(); j++) {
            int cost = a[i - 1] == b[j - 1] ? 0 : 1;
            cur[j] = std::min({prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost});
        }
        std::swap(prev, cur);
    }
    return prev[b.size()];
}

int main() {
    std::cout << levenshtein("kitten", "sitting") << "\n"; // 3: the textbook case
    std::cout << levenshtein("flaw", "lawn") << "\n";      // 2
    std::cout << levenshtein("", "abc") << "\n";           // 3: all insertions
    std::cout << levenshtein("abc", "abc") << "\n";        // 0: identical means 0
    return 0;
}
Output
3
2
3
0

C# v11.0.100

v11.0.100
// Hand-written classic DP (nothing built in): a two-row rolling array, O(len_a*len_b)
static int Levenshtein(string a, string b)
{
    var prev = new int[b.Length + 1];
    for (int j = 0; j <= b.Length; j++) prev[j] = j;
    for (int i = 1; i <= a.Length; i++)
    {
        var cur = new int[b.Length + 1];
        cur[0] = i;
        for (int j = 1; j <= b.Length; j++)
        {
            int cost = a[i - 1] == b[j - 1] ? 0 : 1;
            cur[j] = Math.Min(prev[j] + 1, Math.Min(cur[j - 1] + 1, prev[j - 1] + cost));
        }
        prev = cur;
    }
    return prev[b.Length];
}

Console.WriteLine(Levenshtein("kitten", "sitting")); // 3: the textbook case
Console.WriteLine(Levenshtein("flaw", "lawn"));      // 2
Console.WriteLine(Levenshtein("", "abc"));           // 3: all insertions
Console.WriteLine(Levenshtein("abc", "abc"));        // 0: identical means 0
Output
3
2
3
0

Go v1.27.4

v1.27.4
package main

import "fmt"

// Hand-written classic DP (nothing built in): a two-row rolling array; byte-wise comparison (multi-byte text needs a []rune conversion first)
func levenshtein(a, b string) int {
	prev := make([]int, len(b)+1)
	for j := range prev {
		prev[j] = j
	}
	for i := 1; i <= len(a); i++ {
		cur := make([]int, len(b)+1)
		cur[0] = i
		for j := 1; j <= len(b); j++ {
			cost := 1
			if a[i-1] == b[j-1] {
				cost = 0
			}
			m := prev[j] + 1 // Deletion
			if cur[j-1]+1 < m {
				m = cur[j-1] + 1 // Insertion
			}
			if prev[j-1]+cost < m {
				m = prev[j-1] + cost // Substitution/match
			}
			cur[j] = m
		}
		prev = cur
	}
	return prev[len(b)]
}

func main() {
	fmt.Println(levenshtein("kitten", "sitting")) // 3: the textbook case
	fmt.Println(levenshtein("flaw", "lawn"))      // 2
	fmt.Println(levenshtein("", "abc"))           // 3: all insertions
	fmt.Println(levenshtein("abc", "abc"))        // 0: identical means 0
}
Output
3
2
3
0

Java v27.0.1

v27.0.1
public class Main {
    // Hand-written classic DP (nothing built in): a two-row rolling array
    static int levenshtein(String a, String b) {
        int[] prev = new int[b.length() + 1];
        for (int j = 0; j <= b.length(); j++) prev[j] = j;
        for (int i = 1; i <= a.length(); i++) {
            int[] cur = new int[b.length() + 1];
            cur[0] = i;
            for (int j = 1; j <= b.length(); j++) {
                int cost = a.charAt(i - 1) == b.charAt(j - 1) ? 0 : 1;
                cur[j] = Math.min(prev[j] + 1, Math.min(cur[j - 1] + 1, prev[j - 1] + cost));
            }
            prev = cur;
        }
        return prev[b.length()];
    }

    public static void main(String[] args) {
        System.out.println(levenshtein("kitten", "sitting")); // 3: the textbook case
        System.out.println(levenshtein("flaw", "lawn"));      // 2
        System.out.println(levenshtein("", "abc"));           // 3: all insertions
        System.out.println(levenshtein("abc", "abc"));        // 0: identical means 0
    }
}
Output
3
2
3
0

JavaScript v26.13.1

v26.13.1
// Hand-written classic DP (nothing built in): a two-row rolling array, O(len_a*len_b)
function levenshtein(a, b) {
  let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
  for (let i = 1; i <= a.length; i++) {
    const cur = [i];
    for (let j = 1; j <= b.length; j++) {
      cur.push(Math.min(
        prev[j] + 1,                                    // Deletion
        cur[j - 1] + 1,                                 // Insertion
        prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),  // Substitution/match
      ));
    }
    prev = cur;
  }
  return prev[b.length];
}
console.log(levenshtein("kitten", "sitting")); // 3: the textbook case
console.log(levenshtein("flaw", "lawn")); // 2
console.log(levenshtein("", "abc")); // 3: all insertions
console.log(levenshtein("abc", "abc")); // 0: identical means 0
Output
3
2
3
0

PHP v8.6.0

v8.6.0
// levenshtein: the built-in edit distance — byte-level comparison (transcode or split multi-byte text first)
echo levenshtein("kitten", "sitting"), "\n"; // 3: the textbook case
echo levenshtein("flaw", "lawn"), "\n";      // 2
echo levenshtein("", "abc"), "\n";           // 3: all insertions
echo levenshtein("abc", "abc"), "\n";        // 0: identical means 0
// The three operation costs are customizable (all default to 1)
echo levenshtein("kitten", "sitting", 1, 2, 3), "\n";
Output
3
2
3
0
5

Python v3.15.2

v3.15.2
def levenshtein(a, b):
    # Hand-written classic DP (nothing built in): a two-row rolling array, O(len_a*len_b)
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, 1):
        cur = [i]
        for j, cb in enumerate(b, 1):
            cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
        prev = cur
    return prev[-1]

print(levenshtein("kitten", "sitting"))  # 3: the textbook case
print(levenshtein("flaw", "lawn"))       # 2
print(levenshtein("", "abc"))            # 3: all insertions
print(levenshtein("abc", "abc"))         # 0: identical means 0
Output
3
2
3
0

Rust v1.99.1

v1.99.1
// Hand-written classic DP (nothing built in; strsim crate in real projects): a two-row rolling array iterating over chars
fn levenshtein(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    for i in 1..=a.len() {
        let mut cur = vec![i];
        for j in 1..=b.len() {
            let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
            cur.push((prev[j] + 1).min(cur[j - 1] + 1).min(prev[j - 1] + cost));
        }
        prev = cur;
    }
    prev[b.len()]
}

fn main() {
    println!("{}", levenshtein("kitten", "sitting")); // 3: the textbook case
    println!("{}", levenshtein("flaw", "lawn"));      // 2
    println!("{}", levenshtein("", "abc"));           // 3: all insertions
    println!("{}", levenshtein("abc", "abc"));        // 0: identical means 0
}
Output
3
2
3
0

TypeScript v26.13.1

v26.13.1
// Hand-written classic DP (nothing built in): a two-row rolling array, O(len_a*len_b)
function levenshtein(a: string, b: string): number {
  let prev: number[] = Array.from({ length: b.length + 1 }, (_, j) => j);
  for (let i = 1; i <= a.length; i++) {
    const cur: number[] = [i];
    for (let j = 1; j <= b.length; j++) {
      cur.push(Math.min(
        prev[j] + 1,                                    // Deletion
        cur[j - 1] + 1,                                 // Insertion
        prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),  // Substitution/match
      ));
    }
    prev = cur;
  }
  return prev[b.length];
}
console.log(levenshtein("kitten", "sitting")); // 3: the textbook case
console.log(levenshtein("flaw", "lawn")); // 2
console.log(levenshtein("", "abc")); // 3: all insertions
console.log(levenshtein("abc", "abc")); // 0: identical means 0
Output
3
2
3
0

Language differences

The hand-written DP is this entry's algorithmic teaching core: min of prev[j]+1 (delete), cur[j-1]+1 (insert), prev[j-1]+cost (substitute/match), with two rolling rows dropping space to O(len_b).

C: no built-in — hand-written DP (example, two malloc'd rolling rows); small libraries like libdistance exist.

C++: no built-in — hand-written DP (std::vector rows + std::swap); Boost has no official edit distance.

C#: no built-in — hand-written DP; the .NET BCL has no similarity API.

Go: no built-in — hand-written DP (the example compares bytes; convert to []rune for Chinese); github.com/agnivade/levenshtein is the usual pick.

Java: no built-in — hand-written DP; Apache Commons Text's LevenshteinDistance is the standard dependency.

JavaScript: no built-in — hand-written DP (example); fast-levenshtein on npm wraps the same algorithm.

PHP: levenshtein is built in — but compares bytes (split multibyte Chinese into characters first); the extra parameters customize insertion/substitution/deletion costs (insertion 1 / substitution 2 / deletion 3: two substitutions + one insertion = 5).

Python: no built-in — hand-written DP (example); rapidfuzz (C++-backed, fast, with normalizations) is the norm.

Rust: no built-in — hand-written DP (the example iterates chars); strsim is the usual crate.

TypeScript: same as JavaScript (hand-written DP).