Skip to content
uencoder
TASK

Calculate Levenshtein distance

Levenshtein distance measures the minimum edits (insert, delete, substitute) to transform one string into another. Used in spell checking and fuzzy matching.

  1. 1

    Levenshtein distance is computed with dynamic programming: create a matrix of size (m+1)×(n+1), initialize first row and column with 0..m and 0..n, then for each cell compute min(insert, delete, substitute) based on the previous cells. The distance is in the bottom-right cell. Time and space: O(m×n); space can be optimized to O(min(m,n)) by keeping only two rows.

  2. 2
    Text Diff →

    Compare two texts to see their differences. While text-diff shows line-level changes, Levenshtein operates at character level. Use text-diff for documents and Levenshtein for short strings (words, names, commands).

  3. 3
    Word Count →

    For word-level Levenshtein, tokenize both texts into word arrays and compute the distance on the arrays. This measures word-level edits (insertion, deletion, substitution of words) rather than character-level edits — useful for comparing sentences or paragraphs.

Frequently asked questions

How is Levenshtein distance used in spell checking?
For a misspelled word, compute the Levenshtein distance to each dictionary word. Suggest the dictionary words with the smallest distance (typically 1-2). For efficiency, use a BK-tree (indexes by Levenshtein distance) to avoid comparing against every word. Most spell checkers use this approach.
Levenshtein vs Damerau-Levenshtein?
Levenshtein allows insert, delete, substitute (3 operations). Damerau-Levenshtein adds transposition of adjacent characters (ab → ba in one edit). Damerau is more appropriate for typing errors (adjacent key swaps are common). Both are O(m×n) time and space. Use Damerau for spell checking, Levenshtein for general string comparison.

Workflows that solve this

Learn more

Want to understand why?

Related tools