Programming Search⌘K

Taskcore

Compute the edit distance of two strings

Also called edit distance, Levenshtein distance, string distance, fuzzy match, spelling distance, Wagner-Fischer, minimum edits.

Compute the Levenshtein distance of two strings, the minimum number of one-character insertions, deletions and substitutions that change one into the other, with a dynamic program that keeps two rows.

Task

The Levenshtein distance of two strings "is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character"1. The Rosetta Code task gives the classic example: the distance between kitten and sitting is 3. Replace k with s, replace e with i, and insert g at the end. The distance "is named after Soviet mathematician Vladimir Levenshtein, who introduced it in 1965"2.

The function levenshtein(a, b) returns this distance for two ASCII strings. Upper and lower case letters are different characters, so levenshtein("Apple", "apple") is 1. Wikipedia lists its uses: "Applications include spell checkers, correction of optical character recognition output, and approximate lookup in textual databases."2

This page is about the code in each language. The algorithm, its proof and faster methods are on the algorithm site, in Edit distance.

Solutions

The standard method is a dynamic program. Let d[i][j] be the distance between the first i characters of a and the first j characters of b. Then:

  • d[i][0] is i, because the program deletes i characters.
  • d[0][j] is j, because the program inserts j characters.
  • d[i][j] is the minimum of d[i-1][j] + 1 (delete), d[i][j-1] + 1 (insert) and d[i-1][j-1] + cost, where cost is 0 if the two characters are equal and 1 if not.

The answer is d[len(a)][len(b)]. The full table takes O(mn) time and memory. But "If only the numerical distance is required, each row depends only on the previous row and the current row"2. So all solutions here keep two rows of len(b) + 1 numbers, and swap them after each row. The memory is then O(n).

Language Rows Minimum of three
Python two lists min(x, y, z)
JavaScript, TypeScript two arrays, swapped with a destructuring assignment Math.min(x, y, z)
Java two int[], swapped after each row Math.min(x, Math.min(y, z))
C# two int[] Math.Min(x, Math.Min(y, z))
Go two []int the built-in min(x, y, z)
Rust two Vec<usize> and std::mem::swap x.min(y).min(z)
C two arrays from malloc a small helper
C++ two std::vector<std::size_t> and std::swap std::min({x, y, z})
Bash two indexed arrays tests in (( ))
  • Python. The standard library has no Levenshtein function. difflib.SequenceMatcher computes a ratio of a different kind. Packages on PyPI give fast versions in C.
  • Rust and C++. The solutions swap the two rows with std::mem::swap or std::swap, so no row is copied.
  • C. The function allocates two rows of len(b) + 1 numbers and frees them before it returns. It returns -1 if the allocation fails.
  • Bash. The function works on the characters of the two strings with ${a:i-1:1}. It is slow for long strings, because each step of the loop runs in the shell. Use it for short words only.

Python, with the examples of the Rosetta Code task:

def levenshtein(a, 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"))
print(levenshtein("rosettacode", "raisethysword"))
print(levenshtein("edocattesor", "drowsyhtesiar"))
print(levenshtein("ab", "ba"), levenshtein("", "abc"))
Output
3
8
8
2 3

The third line uses the two strings in reverse. The task notes that "The distance between two strings is same as that when both strings are reversed."1

Edge cases

  • Empty strings. The distance from the empty string to abc is 3, the length of abc. Two empty strings have the distance 0.
  • Equal strings. The distance is 0.
  • A swap of two characters. ab and ba have the distance 2, not 1, because Levenshtein has no swap operation. The Damerau-Levenshtein distance "additionally allows a transposition of two adjacent symbols"2.
  • Case. Apple and apple have the distance 1.
  • Bounds. The distance is at least the difference of the two lengths, and at most the longer length. Wikipedia explains the lower bound: "a single insertion or deletion changes the string length by only one"2. abc and abcdef have the distance 3, and abc and xyz also have the distance 3.

Pitfalls

  • Bytes are not characters. In Go, "A string's bytes can be accessed by integer indices"3. A loop over s[i] compares bytes, and é is 2 bytes in UTF-8:

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

func distance(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
			}
			cur[j] = min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost)
		}
		prev = cur
	}
	return prev[len(b)]
}

func main() {
	fmt.Println(len("café"), distance("café", "cafe"))
	fmt.Println(len([]rune("café")))
}
Output
5 2
4

The distance of café and cafe is 1. A conversion to []rune gives "a slice containing the individual Unicode code points of the string"3. The same problem occurs in C and Rust with bytes, and in JavaScript, Java and C# with UTF-16 code units for characters outside the Basic Multilingual Plane.

  • A full table for long strings. Two strings of 100,000 characters need a table of 10^10 numbers. Keep two rows.
  • Recursion without a table. The recursive definition calls itself three times at each step, so a direct translation takes exponential time. Use the table, or a cache.
  • A distance is not a similarity. A distance of 3 is small for two long strings and large for two short ones. To compare, divide by the longer length, or use a similarity ratio.

Code

The build runs the native tests of each language in a pinned toolchain.

levenshtein.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.


def levenshtein(a: str, b: str) -> int:
    """Return the minimum number of one-character insertions, deletions and
    substitutions that change a into b. Two rows of the table are kept."""
    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]


if __name__ == "__main__":
    print(levenshtein("kitten", "sitting"))
test_levenshtein.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

import pytest

from levenshtein import levenshtein

CASES = [
    ("kitten-sitting", "kitten", "sitting", 3),
    ("rosettacode", "rosettacode", "raisethysword", 8),
    ("flaw-lawn", "flaw", "lawn", 2),
    ("both-empty", "", "", 0),
    ("empty-left", "", "abc", 3),
    ("empty-right", "abc", "", 3),
    ("equal", "same", "same", 0),
    ("one-substitution", "a", "b", 1),
    ("transposition", "ab", "ba", 2),
    ("case", "Apple", "apple", 1),
    ("disjoint", "abc", "xyz", 3),
    ("prefix", "abc", "abcdef", 3),
    ("intention", "intention", "execution", 5),
    ("space", "a b", "ab", 1),
]


@pytest.mark.parametrize(("name", "a", "b", "want"), CASES, ids=[c[0] for c in CASES])
def test_levenshtein(name, a, b, want):
    assert levenshtein(a, b) == want
    assert levenshtein(b, a) == want
levenshtein.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

#ifndef LEVENSHTEIN_HPP
#define LEVENSHTEIN_HPP

#include <algorithm>
#include <cstddef>
#include <numeric>
#include <string_view>
#include <utility>
#include <vector>

// Returns the minimum number of one-character insertions, deletions and
// substitutions that change a into b. Two rows of the table are kept.
inline std::size_t levenshtein(std::string_view a, std::string_view b) {
    std::vector<std::size_t> prev(b.size() + 1);
    std::vector<std::size_t> cur(b.size() + 1);
    std::iota(prev.begin(), prev.end(), std::size_t{0});
    for (std::size_t i = 1; i <= a.size(); ++i) {
        cur[0] = i;
        for (std::size_t j = 1; j <= b.size(); ++j) {
            const std::size_t 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()];
}

#endif
test_levenshtein.cpp 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

#include <cstddef>
#include <cstdio>

#include "levenshtein.hpp"

namespace {

struct test_case {
    const char* name;
    const char* a;
    const char* b;
    std::size_t want;
};

const test_case cases[] = {
    {"kitten-sitting", "kitten", "sitting", 3},
    {"rosettacode", "rosettacode", "raisethysword", 8},
    {"flaw-lawn", "flaw", "lawn", 2},
    {"both-empty", "", "", 0},
    {"empty-left", "", "abc", 3},
    {"empty-right", "abc", "", 3},
    {"equal", "same", "same", 0},
    {"one-substitution", "a", "b", 1},
    {"transposition", "ab", "ba", 2},
    {"case", "Apple", "apple", 1},
    {"disjoint", "abc", "xyz", 3},
    {"prefix", "abc", "abcdef", 3},
    {"intention", "intention", "execution", 5},
    {"space", "a b", "ab", 1},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        if (levenshtein(c.a, c.b) != c.want || levenshtein(c.b, c.a) != c.want) {
            std::printf("FAIL %s\n", c.name);
            ++failures;
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Levenshtein.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

/** The Levenshtein distance of two strings. */
public final class Levenshtein {
    private Levenshtein() {}

    /**
     * Returns the minimum number of one-character insertions, deletions and
     * substitutions that change a into b. Two rows of the table are kept.
     */
    public static int levenshtein(String a, String b) {
        int[] prev = new int[b.length() + 1];
        int[] cur = new int[b.length() + 1];
        for (int j = 0; j <= b.length(); j++) {
            prev[j] = j;
        }
        for (int i = 1; i <= a.length(); i++) {
            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] + cost, Math.min(prev[j], cur[j - 1]) + 1);
            }
            int[] t = prev;
            prev = cur;
            cur = t;
        }
        return prev[b.length()];
    }

    public static void main(String[] args) {
        System.out.println(levenshtein("kitten", "sitting"));
    }
}
LevenshteinTest.java 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class LevenshteinTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("kitten-sitting", "kitten", "sitting", 3),
                Arguments.of("rosettacode", "rosettacode", "raisethysword", 8),
                Arguments.of("flaw-lawn", "flaw", "lawn", 2),
                Arguments.of("both-empty", "", "", 0),
                Arguments.of("empty-left", "", "abc", 3),
                Arguments.of("empty-right", "abc", "", 3),
                Arguments.of("equal", "same", "same", 0),
                Arguments.of("one-substitution", "a", "b", 1),
                Arguments.of("transposition", "ab", "ba", 2),
                Arguments.of("case", "Apple", "apple", 1),
                Arguments.of("disjoint", "abc", "xyz", 3),
                Arguments.of("prefix", "abc", "abcdef", 3),
                Arguments.of("intention", "intention", "execution", 5),
                Arguments.of("space", "a b", "ab", 1)
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void levenshtein(String name, String a, String b, int want) {
        assertEquals(want, Levenshtein.levenshtein(a, b));
        assertEquals(want, Levenshtein.levenshtein(b, a));
    }
}
levenshtein.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

#include "levenshtein.h"

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

static int min3(int x, int y, int z) {
    int m = x < y ? x : y;
    return m < z ? m : z;
}

int levenshtein(const char *a, const char *b) {
    size_t m = strlen(a);
    size_t n = strlen(b);
    int *prev = malloc((n + 1) * sizeof *prev);
    int *cur = malloc((n + 1) * sizeof *cur);
    if (prev == NULL || cur == NULL) {
        free(prev);
        free(cur);
        return -1;
    }
    for (size_t j = 0; j <= n; j++) {
        prev[j] = (int)j;
    }
    for (size_t i = 1; i <= m; i++) {
        cur[0] = (int)i;
        for (size_t j = 1; j <= n; j++) {
            int cost = a[i - 1] == b[j - 1] ? 0 : 1;
            cur[j] = min3(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
        }
        int *t = prev;
        prev = cur;
        cur = t;
    }
    int result = prev[n];
    free(prev);
    free(cur);
    return result;
}
levenshtein.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

#ifndef LEVENSHTEIN_H
#define LEVENSHTEIN_H

// Returns the minimum number of one-character insertions, deletions and
// substitutions that change a into b, or -1 if there is no memory for the
// two rows of the table.
int levenshtein(const char *a, const char *b);

#endif
test_levenshtein.c 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

#include "levenshtein.h"

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

struct test_case {
    const char *name;
    const char *a;
    const char *b;
    int want;
};

static const struct test_case cases[] = {
    {"kitten-sitting", "kitten", "sitting", 3},
    {"rosettacode", "rosettacode", "raisethysword", 8},
    {"flaw-lawn", "flaw", "lawn", 2},
    {"both-empty", "", "", 0},
    {"empty-left", "", "abc", 3},
    {"empty-right", "abc", "", 3},
    {"equal", "same", "same", 0},
    {"one-substitution", "a", "b", 1},
    {"transposition", "ab", "ba", 2},
    {"case", "Apple", "apple", 1},
    {"disjoint", "abc", "xyz", 3},
    {"prefix", "abc", "abcdef", 3},
    {"intention", "intention", "execution", 5},
    {"space", "a b", "ab", 1},
};

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        int got = levenshtein(c->a, c->b);
        int back = levenshtein(c->b, c->a);
        if (got != c->want || back != c->want) {
            printf("FAIL %s: got %d and %d\n", c->name, got, back);
            failures++;
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Levenshtein.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

using System;

/// <summary>The Levenshtein distance of two strings.</summary>
public static class Levenshtein
{
    /// <summary>
    /// Returns the minimum number of one-character insertions, deletions and
    /// substitutions that change a into b. Two rows of the table are kept.
    /// </summary>
    public static int Distance(string a, string b)
    {
        var prev = new int[b.Length + 1];
        var cur = new int[b.Length + 1];
        for (var j = 0; j <= b.Length; j++)
        {
            prev[j] = j;
        }
        for (var i = 1; i <= a.Length; i++)
        {
            cur[0] = i;
            for (var j = 1; j <= b.Length; j++)
            {
                var cost = a[i - 1] == b[j - 1] ? 0 : 1;
                cur[j] = Math.Min(prev[j - 1] + cost, Math.Min(prev[j], cur[j - 1]) + 1);
            }
            (prev, cur) = (cur, prev);
        }
        return prev[b.Length];
    }
}
LevenshteinTests.cs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

using Xunit;

public sealed class LevenshteinTests
{
    public static TheoryData<string, string, string, int> Cases => new()
    {
        { "kitten-sitting", "kitten", "sitting", 3 },
        { "rosettacode", "rosettacode", "raisethysword", 8 },
        { "flaw-lawn", "flaw", "lawn", 2 },
        { "both-empty", "", "", 0 },
        { "empty-left", "", "abc", 3 },
        { "empty-right", "abc", "", 3 },
        { "equal", "same", "same", 0 },
        { "one-substitution", "a", "b", 1 },
        { "transposition", "ab", "ba", 2 },
        { "case", "Apple", "apple", 1 },
        { "disjoint", "abc", "xyz", 3 },
        { "prefix", "abc", "abcdef", 3 },
        { "intention", "intention", "execution", 5 },
        { "space", "a b", "ab", 1 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Distance(string name, string a, string b, int want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Levenshtein.Distance(a, b));
        Assert.Equal(want, Levenshtein.Distance(b, a));
    }
}
levenshtein.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

/**
 * Returns the minimum number of one-character insertions, deletions and
 * substitutions that change a into b. Two rows of the table are kept.
 */
export function levenshtein(a, b) {
  let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
  let cur = new Array(b.length + 1).fill(0);
  for (let i = 1; i <= a.length; i++) {
    cur[0] = i;
    for (let j = 1; j <= b.length; j++) {
      const cost = a[i - 1] === b[j - 1] ? 0 : 1;
      cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
    }
    [prev, cur] = [cur, prev];
  }
  return prev[b.length];
}
levenshtein.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { levenshtein } from "./levenshtein.js";

const cases = [
  ["kitten-sitting", "kitten", "sitting", 3],
  ["rosettacode", "rosettacode", "raisethysword", 8],
  ["flaw-lawn", "flaw", "lawn", 2],
  ["both-empty", "", "", 0],
  ["empty-left", "", "abc", 3],
  ["empty-right", "abc", "", 3],
  ["equal", "same", "same", 0],
  ["one-substitution", "a", "b", 1],
  ["transposition", "ab", "ba", 2],
  ["case", "Apple", "apple", 1],
  ["disjoint", "abc", "xyz", 3],
  ["prefix", "abc", "abcdef", 3],
  ["intention", "intention", "execution", 5],
  ["space", "a b", "ab", 1],
];

for (const [name, a, b, want] of cases) {
  test(name, () => {
    assert.equal(levenshtein(a, b), want);
    assert.equal(levenshtein(b, a), want);
  });
}
levenshtein.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

/**
 * Returns the minimum number of one-character insertions, deletions and
 * substitutions that change a into b. Two rows of the table are kept.
 */
export function levenshtein(a: string, b: string): number {
  let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
  let cur = new Array(b.length + 1).fill(0);
  for (let i = 1; i <= a.length; i++) {
    cur[0] = i;
    for (let j = 1; j <= b.length; j++) {
      const cost = a[i - 1] === b[j - 1] ? 0 : 1;
      cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
    }
    [prev, cur] = [cur, prev];
  }
  return prev[b.length];
}
levenshtein.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { levenshtein } from "./levenshtein.ts";

const cases: [string, string, string, number][] = [
  ["kitten-sitting", "kitten", "sitting", 3],
  ["rosettacode", "rosettacode", "raisethysword", 8],
  ["flaw-lawn", "flaw", "lawn", 2],
  ["both-empty", "", "", 0],
  ["empty-left", "", "abc", 3],
  ["empty-right", "abc", "", 3],
  ["equal", "same", "same", 0],
  ["one-substitution", "a", "b", 1],
  ["transposition", "ab", "ba", 2],
  ["case", "Apple", "apple", 1],
  ["disjoint", "abc", "xyz", 3],
  ["prefix", "abc", "abcdef", 3],
  ["intention", "intention", "execution", 5],
  ["space", "a b", "ab", 1],
];

for (const [name, a, b, want] of cases) {
  test(name, () => {
    assert.equal(levenshtein(a, b), want);
    assert.equal(levenshtein(b, a), want);
  });
}
levenshtein.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

// Package levenshtein computes the Levenshtein distance of two strings.
package levenshtein

// Distance returns the minimum number of one-character insertions, deletions
// and substitutions that change a into b. The text is ASCII, so the function
// compares bytes. For other text, convert a and b to []rune first.
func Distance(a, b string) int {
	prev := make([]int, len(b)+1)
	cur := make([]int, len(b)+1)
	for j := range prev {
		prev[j] = j
	}
	for i := 1; i <= len(a); i++ {
		cur[0] = i
		for j := 1; j <= len(b); j++ {
			cost := 1
			if a[i-1] == b[j-1] {
				cost = 0
			}
			cur[j] = min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost)
		}
		prev, cur = cur, prev
	}
	return prev[len(b)]
}
levenshtein_test.go 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

package levenshtein

import "testing"

var cases = []struct {
	name string
	a    string
	b    string
	want int
}{
	{"kitten-sitting", "kitten", "sitting", 3},
	{"rosettacode", "rosettacode", "raisethysword", 8},
	{"flaw-lawn", "flaw", "lawn", 2},
	{"both-empty", "", "", 0},
	{"empty-left", "", "abc", 3},
	{"empty-right", "abc", "", 3},
	{"equal", "same", "same", 0},
	{"one-substitution", "a", "b", 1},
	{"transposition", "ab", "ba", 2},
	{"case", "Apple", "apple", 1},
	{"disjoint", "abc", "xyz", 3},
	{"prefix", "abc", "abcdef", 3},
	{"intention", "intention", "execution", 5},
	{"space", "a b", "ab", 1},
}

func TestDistance(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := Distance(c.a, c.b); got != c.want {
				t.Fatalf("Distance(%q, %q) = %d, want %d", c.a, c.b, got, c.want)
			}
			if got := Distance(c.b, c.a); got != c.want {
				t.Fatalf("Distance(%q, %q) = %d, want %d", c.b, c.a, got, c.want)
			}
		})
	}
}
levenshtein.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

/// Returns the minimum number of one-character insertions, deletions and
/// substitutions that change a into b. The text is ASCII, so the function
/// compares bytes. For other text, collect `chars()` into vectors first.
pub fn levenshtein(a: &str, b: &str) -> usize {
    let (a, b) = (a.as_bytes(), b.as_bytes());
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    let mut cur = vec![0; b.len() + 1];
    for (i, &ca) in a.iter().enumerate() {
        cur[0] = i + 1;
        for (j, &cb) in b.iter().enumerate() {
            let cost = usize::from(ca != cb);
            cur[j + 1] = (prev[j + 1] + 1).min(cur[j] + 1).min(prev[j] + cost);
        }
        std::mem::swap(&mut prev, &mut cur);
    }
    prev[b.len()]
}
tests/levenshtein_test.rs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

use algo_compute_the_edit_distance_of_two_strings::levenshtein;

const CASES: &[(&str, &str, &str, usize)] = &[
    ("kitten-sitting", "kitten", "sitting", 3),
    ("rosettacode", "rosettacode", "raisethysword", 8),
    ("flaw-lawn", "flaw", "lawn", 2),
    ("both-empty", "", "", 0),
    ("empty-left", "", "abc", 3),
    ("empty-right", "abc", "", 3),
    ("equal", "same", "same", 0),
    ("one-substitution", "a", "b", 1),
    ("transposition", "ab", "ba", 2),
    ("case", "Apple", "apple", 1),
    ("disjoint", "abc", "xyz", 3),
    ("prefix", "abc", "abcdef", 3),
    ("intention", "intention", "execution", 5),
    ("space", "a b", "ab", 1),
];

#[test]
fn cases() {
    for &(name, a, b, want) in CASES {
        assert_eq!(levenshtein(a, b), want, "{name}");
        assert_eq!(levenshtein(b, a), want, "{name} swapped");
    }
}
levenshtein.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

# levenshtein a b: print the minimum number of one-character insertions,
# deletions and substitutions that change a into b. Two rows of the table
# are kept. Each step runs in the shell, so use it for short words only.
levenshtein() {
  local a=$1 b=$2 i j cost best
  local -a prev cur
  for ((j = 0; j <= ${#b}; j++)); do
    prev[j]=$j
  done
  for ((i = 1; i <= ${#a}; i++)); do
    cur=("$i")
    for ((j = 1; j <= ${#b}; j++)); do
      cost=1
      [[ ${a:i-1:1} == "${b:j-1:1}" ]] && cost=0
      best=$((prev[j - 1] + cost))
      ((prev[j] + 1 < best)) && best=$((prev[j] + 1))
      ((cur[j - 1] + 1 < best)) && best=$((cur[j - 1] + 1))
      cur[j]=$best
    done
    prev=("${cur[@]}")
  done
  echo "${prev[${#b}]}"
}
test_levenshtein.bats 119 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/compute-the-edit-distance-of-two-strings/.

setup() {
  source "$BATS_TEST_DIRNAME/levenshtein.sh"
}

@test "kitten-sitting" {
  run levenshtein 'kitten' 'sitting'
  [ "$status" -eq 0 ]
  [ "$output" = 3 ]
  run levenshtein 'sitting' 'kitten'
  [ "$output" = 3 ]
}

@test "rosettacode" {
  run levenshtein 'rosettacode' 'raisethysword'
  [ "$status" -eq 0 ]
  [ "$output" = 8 ]
  run levenshtein 'raisethysword' 'rosettacode'
  [ "$output" = 8 ]
}

@test "flaw-lawn" {
  run levenshtein 'flaw' 'lawn'
  [ "$status" -eq 0 ]
  [ "$output" = 2 ]
  run levenshtein 'lawn' 'flaw'
  [ "$output" = 2 ]
}

@test "both-empty" {
  run levenshtein '' ''
  [ "$status" -eq 0 ]
  [ "$output" = 0 ]
  run levenshtein '' ''
  [ "$output" = 0 ]
}

@test "empty-left" {
  run levenshtein '' 'abc'
  [ "$status" -eq 0 ]
  [ "$output" = 3 ]
  run levenshtein 'abc' ''
  [ "$output" = 3 ]
}

@test "empty-right" {
  run levenshtein 'abc' ''
  [ "$status" -eq 0 ]
  [ "$output" = 3 ]
  run levenshtein '' 'abc'
  [ "$output" = 3 ]
}

@test "equal" {
  run levenshtein 'same' 'same'
  [ "$status" -eq 0 ]
  [ "$output" = 0 ]
  run levenshtein 'same' 'same'
  [ "$output" = 0 ]
}

@test "one-substitution" {
  run levenshtein 'a' 'b'
  [ "$status" -eq 0 ]
  [ "$output" = 1 ]
  run levenshtein 'b' 'a'
  [ "$output" = 1 ]
}

@test "transposition" {
  run levenshtein 'ab' 'ba'
  [ "$status" -eq 0 ]
  [ "$output" = 2 ]
  run levenshtein 'ba' 'ab'
  [ "$output" = 2 ]
}

@test "case" {
  run levenshtein 'Apple' 'apple'
  [ "$status" -eq 0 ]
  [ "$output" = 1 ]
  run levenshtein 'apple' 'Apple'
  [ "$output" = 1 ]
}

@test "disjoint" {
  run levenshtein 'abc' 'xyz'
  [ "$status" -eq 0 ]
  [ "$output" = 3 ]
  run levenshtein 'xyz' 'abc'
  [ "$output" = 3 ]
}

@test "prefix" {
  run levenshtein 'abc' 'abcdef'
  [ "$status" -eq 0 ]
  [ "$output" = 3 ]
  run levenshtein 'abcdef' 'abc'
  [ "$output" = 3 ]
}

@test "intention" {
  run levenshtein 'intention' 'execution'
  [ "$status" -eq 0 ]
  [ "$output" = 5 ]
  run levenshtein 'execution' 'intention'
  [ "$output" = 5 ]
}

@test "space" {
  run levenshtein 'a b' 'ab'
  [ "$status" -eq 0 ]
  [ "$output" = 1 ]
  run levenshtein 'ab' 'a b'
  [ "$output" = 1 ]
}

References

  1. Rosetta Code, Levenshtein distance (task text, from acmeism/RosettaCodeData), task text
  2. Levenshtein distance, Wikipedia, Introduction; Properties and bounds; Applications; Relationship to other string distances; Memory reduction and edit-script reconstruction
  3. The Go Programming Language Specification, String types; Conversions to and from a string type

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source