Levenshtein distance is the smallest number of single-character insertions, deletions and substitutions that turn one string into another. It’s the most common form of edit distance. kitten and sitting are 3 edits apart, for example, and kiten and kitten are 1 edit apart.
In this guide, we’ll walk through the algorithm with a worked example, give you a calculator to try your own strings, write it in Python and JavaScript, and cover its speed, accuracy and related algorithms. We’ll finish with how Typesense uses the same idea for typo tolerance.
Note: The code uses Python 3.15 with
Levenshtein0.27.5, Node.js 26 withfastest-levenshtein1.0.16, and Typesense 30.2.
The Problem: Matching a Typo to the Right Word
Say you’re building a “Did you mean?” feature for a search box. A user types kiten, and your vocabulary holds five words:
kitten, mitten, kitchen, sitting, knitting
An exact or substring comparison finds nothing, since kiten isn’t any of the five words or inside them. You need a number that says how far apart two strings are, so you can sort the vocabulary by it and suggest the closest word.
Levenshtein distance is that number. Vladimir Levenshtein introduced it in 1965, and today it sits behind spell checkers, record deduplication and fuzzy search. Each of the three edits costs 1:
insertion: kiten → kitten (insert t)
deletion: kitten → kiten (delete t)
substitution: kiten → miten (k becomes m)
Of all the edit sequences that turn one string into another, the distance is the length of the shortest.
How the Levenshtein Distance Algorithm Works
The standard method, usually credited to Wagner and Fischer (1974), uses dynamic programming. It solves the problem for every pair of prefixes, short ones first, and builds each answer from ones it already has.
The Levenshtein Distance Formula
For strings a and b, let d[i][j] be the distance between the first i characters of a and the first j characters of b. Turning a prefix into the empty string takes one deletion per character, so d[i][0] = i and d[0][j] = j. Every other cell takes the cheapest of three moves:
d[i][j] = min(
d[i-1][j] + 1, # delete a[i-1]
d[i][j-1] + 1, # insert b[j-1]
d[i-1][j-1] + cost # substitute, where cost = 0 if a[i-1] == b[j-1], else 1
)
The answer is the bottom-right cell, d[len(a)][len(b)].
Levenshtein Distance Example: kiten → mitten
Press Play to watch the matrix for kiten (rows) and mitten (columns) fill one cell at a time:
Each cell holds the edits that turn the letters up to its row into the letters up to its column. The cell in row i, column m turns ki into m. ∅ stands for the empty string.
A cell takes the smallest of three options, one per neighbor:
- Above means delete. The cell above plus 1, for deleting the row’s last letter.
- Left means insert. The cell to the left plus 1, for inserting the column’s last letter.
- Upper-left means substitute. The upper-left cell plus 1 for replacing the row’s last letter with the column’s, or plus 0 when they match.
The bottom-right cell covers both whole words, so the distance is 2. The animation then walks back through the cells each value came from. On that path, the sideways step is the inserted t, the final step into the top-left corner is the substitution of k with m, and the rest are free matches.
Running the same calculation against the whole vocabulary gives this ranking:
| Word | Distance from kiten |
|---|---|
| kitten | 1 |
| mitten | 2 |
| kitchen | 2 |
| sitting | 4 |
| knitting | 4 |
So kitten is the suggestion. Notice the tie between mitten and kitchen, which the distance alone can’t break.
Levenshtein Distance Calculator
Type any two strings into this online calculator to see their distance, the edits that produce it, and the matrix with one cheapest path highlighted. It starts with the worked example:
Try kitetn and kitten, then tick the checkbox. Plain Levenshtein counts the swapped t and e as two substitutions, while the Damerau variant counts one swap.
Levenshtein Distance in Python
Each row only needs the row above it, so you don’t need the whole table. This version keeps two rows, so memory grows with the shorter string instead of len(a) × len(b):
def levenshtein(a: str, b: str) -> int:
# Keep the shorter string in b, so each row is as short as possible
if len(a) < len(b):
a, b = b, a
previous = list(range(len(b) + 1)) # row 0: "" -> b[:j] takes j inserts
for i, char_a in enumerate(a, start=1):
current = [i] # column 0: a[:i] -> "" takes i deletes
for j, char_b in enumerate(b, start=1):
cost = 0 if char_a == char_b else 1
current.append(min(
previous[j] + 1, # deletion
current[j - 1] + 1, # insertion
previous[j - 1] + cost, # substitution (or match)
))
previous = current
return previous[-1]
words = ["kitten", "mitten", "kitchen", "sitting", "knitting"]
query = "kiten"
for word in sorted(words, key=lambda w: levenshtein(query, w)):
print(word, levenshtein(query, word))
Swapping a and b is safe, since the distance is the same in both directions. The script prints the same ranking as the table above.
For real workloads, use the Levenshtein package, a C extension from the RapidFuzz project. Install it with pip:
pip install Levenshtein
Levenshtein.distance takes the same two strings. Its score_cutoff argument caps the distance, which saves work when you only care about close matches:
import Levenshtein
print(Levenshtein.distance("kiten", "mitten")) # 2
print(Levenshtein.distance("kiten", "sitting", score_cutoff=2)) # 3
The second call returns 3 rather than 4, because the library returns score_cutoff + 1 once the distance passes the cutoff. Also note that Levenshtein.ratio is an Indel similarity that counts insertions and deletions only, so it isn’t 1 - distance / length.
Levenshtein Distance in JavaScript
This is a line-for-line port of the Python version. Save it as levenshtein.mjs:
function levenshtein(a, b) {
// Keep the shorter string in b, so each row is as short as possible
if (a.length < b.length) [a, b] = [b, a];
let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
for (let i = 1; i <= a.length; i++) {
const current = [i];
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
current[j] = Math.min(
previous[j] + 1, // deletion
current[j - 1] + 1, // insertion
previous[j - 1] + cost // substitution (or match)
);
}
previous = current;
}
return previous[b.length];
}
const words = ["kitten", "mitten", "kitchen", "sitting", "knitting"];
const query = "kiten";
words
.map((word) => [word, levenshtein(query, word)])
.sort((x, y) => x[1] - y[1])
.forEach(([word, distance]) => console.log(word, distance));
It prints the same ranking. One catch is that a[i] indexes UTF-16 code units, so an emoji counts as two characters. Pass Array.from(a) and Array.from(b) instead if your input can contain them.
The fastest-levenshtein package gives you distance and a closest helper that returns the nearest word in a list. Install it with npm:
npm install fastest-levenshtein
Then add the import to the same levenshtein.mjs file, since import needs an ES module:
import { distance, closest } from "fastest-levenshtein";
console.log(distance("kiten", "mitten")); // 2
console.log(closest("kiten", words)); // "kitten"
Pros and Cons of Levenshtein Distance
Levenshtein distance needs no training data or language rules, it’s exact, and it’s easy to explain. It’s also a true metric. It’s never negative, it’s symmetric, and it obeys the triangle inequality, which lets structures such as BK-trees skip whole branches of a dictionary during a lookup. The trade-offs show up once you use it for search.
Speed
Filling the matrix takes len(a) × len(b) steps. That’s hard to beat, since a 2015 result showed no algorithm does it in strongly subquadratic time unless a widely believed complexity hypothesis (SETH) is false.
The constant factor still matters. We timed 100,000 pairs of random 8-letter words, best of 5 runs, with Python and Node.js each in Docker on an Apple M5 Pro with 24 GB of RAM:
| Implementation | Time for 100,000 pairs |
|---|---|
| Pure Python (the function above) | 378 ms |
Levenshtein 0.27.5 | 10 ms |
| Pure JavaScript (the function above) | 45 ms |
fastest-levenshtein 1.0.16 | 4 ms |
Your numbers will differ. Compare each library with the plain version in its own language. Both libraries use bit-parallel algorithms, which pack a column of the matrix into the bits of a machine word. Levenshtein uses Hyyrö’s algorithm for short strings, and fastest-levenshtein uses Myers’ algorithm (1999).
To reproduce the numbers, append each benchmark to the matching script from the sections above:
Benchmark code (Python)
import random
import string
import timeit
import Levenshtein
random.seed(42)
random_word = lambda: "".join(random.choices(string.ascii_lowercase, k=8))
pairs = [(random_word(), random_word()) for _ in range(100_000)]
for name, fn in [("pure Python", levenshtein), ("Levenshtein", Levenshtein.distance)]:
best = min(timeit.repeat(lambda: [fn(a, b) for a, b in pairs], number=1, repeat=5))
print(f"{name}: {best * 1000:.0f} ms")
Benchmark code (JavaScript)
const letters = "abcdefghijklmnopqrstuvwxyz";
const randomWord = () => Array.from({ length: 8 }, () => letters[Math.floor(Math.random() * 26)]).join("");
const pairs = Array.from({ length: 100_000 }, () => [randomWord(), randomWord()]);
for (const [name, fn] of [["pure JavaScript", levenshtein], ["fastest-levenshtein", distance]]) {
let best = Infinity;
for (let run = 0; run < 5; run++) {
const start = performance.now();
for (const [a, b] of pairs) fn(a, b);
best = Math.min(best, performance.now() - start);
}
console.log(`${name}: ${best.toFixed(0)} ms`);
}
The bigger problem in search is the number of comparisons. Checking a query against a million-word vocabulary means a million matrices for every keystroke, which is why search engines index the vocabulary instead.
Accuracy
A few things the plain distance gets wrong:
- Swapped letters cost 2.
kitetnis one slip away fromkitten, but plain Levenshtein counts two substitutions. In Python,rapidfuzz.distance.OSA.distancecounts the swap as 1, and RapidFuzz comes installed withLevenshtein. - The count ignores length. Two edits turn
catintocow, a different word, andencyclopediainto the typoencyclopdeia. Normalize by length, or allow more typos only on longer words. - Ties and context. The distance can’t break the
mittenandkitchentie, and it knows nothing about keyboard layout or word popularity. - Case and Unicode.
Kittenis 1 edit fromkitten, and acaféwith a combining accent is 2 edits from a precomposed one. Lowercase and apply Unicode NFC normalization first.
Levenshtein vs Damerau-Levenshtein, Jaro-Winkler and Others
Each related string measure suits a different job:
| Algorithm | What it counts | Best for |
|---|---|---|
| Levenshtein | Insertions, deletions, substitutions | General spelling distance |
| Damerau-Levenshtein (OSA) | The same, plus adjacent swaps | Typing errors, search typo tolerance |
| Hamming | Substitutions only, equal lengths | Fixed-length codes and hashes |
| Longest common subsequence | Insertions and deletions only | diff tools, Levenshtein.ratio |
| Jaro-Winkler | Shared characters, with a prefix bonus | Names in record linkage |
| Levenshtein automaton | Distance up to a limit, as a state machine | Searching a dictionary, as Lucene does |
In short, use Levenshtein distance for two strings or a short list, add the Damerau swap for typed input, and switch to an index for a large vocabulary.
How Typesense Uses Levenshtein Distance
Typesense doesn’t compare the query with each word one by one. It stores every indexed word in an adaptive radix tree, a kind of trie where words with a shared prefix share a path, and computes the distance while it walks the tree.
Each step down the tree adds one matrix row, so kitten and kitchen share the rows for kit. A branch is abandoned when its cost passes the typo limit and looks unlikely to recover, so most words never get a full matrix. Typesense also applies the adjacent-swap rule, so it uses the OSA form of Damerau-Levenshtein distance.
Let’s load the same five words into a collection:
curl "http://localhost:8108/collections" \
-X POST \
-H "Content-Type: application/json" \
-H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
-d '{
"name": "words",
"fields": [{"name": "word", "type": "string"}]
}'
Then import the words as JSONL:
curl "http://localhost:8108/collections/words/documents/import?action=create" \
-X POST \
-H "Content-Type: text/plain" \
-H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" \
--data-binary '{"id": "1", "word": "kitten"}
{"id": "2", "word": "mitten"}
{"id": "3", "word": "kitchen"}
{"id": "4", "word": "sitting"}
{"id": "5", "word": "knitting"}'
Each line comes back as {"success":true}. Now search for kiten:
curl "http://localhost:8108/collections/words/documents/search?q=kiten&query_by=word&prefix=false" \
-H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}"
Prefix search is on by default, and q=kit would match kitchen and kitten as prefixes, so we set prefix=false to compare whole words, as our Python function does. It returns only kitten:
{
"found": 1,
"hits": [
{
"document": { "id": "1", "word": "kitten" },
"text_match": 578730054645713017
}
]
}
That’s two defaults at work. min_len_2typo is 7, so the 5-letter kiten gets at most 1 typo, which is the length rule from the accuracy section. typo_tokens_threshold is 1, so Typesense stops looking for more distant words once it has one result. To see more of the ranking, allow 2 typos on 5-letter words and raise the threshold:
curl "http://localhost:8108/collections/words/documents/search?q=kiten&query_by=word&prefix=false&min_len_2typo=5&typo_tokens_threshold=5" \
-H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}"
This returns kitten first, then kitchen and mitten with equal scores, which is the same tie we found by hand:
{
"found": 3,
"hits": [
{ "document": { "id": "1", "word": "kitten" }, "text_match": 578730054645713017 },
{ "document": { "id": "3", "word": "kitchen" }, "text_match": 578729985926236281 },
{ "document": { "id": "2", "word": "mitten" }, "text_match": 578729985926236281 }
]
}
sitting and knitting are 4 edits away, beyond the num_typos maximum of 2, so they don’t match. The swap rule is easy to see with kitetn, which plain Levenshtein puts 2 edits from kitten:
curl "http://localhost:8108/collections/words/documents/search?q=kitetn&query_by=word&prefix=false&num_typos=1" \
-H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}"
It returns kitten ("found": 1) even with num_typos=1, because the swap counts as one edit.
Typesense keeps its index in memory, so you size the server’s RAM for your data. It’s built as a search index, so keep your records in a primary database and sync them to Typesense. If you need the exact edit distance for each hit, compute it in your app, since the response reports a ranking score rather than the distance.
Conclusion
Computing Levenshtein distance yourself is the right call for two strings or a list of a few thousand, such as deduplicating records or a “Did you mean?” over a small, fixed vocabulary. Use the Levenshtein or fastest-levenshtein package rather than the plain loop, since they were 10 to 40 times faster in our test.
Once you search a large or changing collection as the user types, the number of comparisons becomes the problem, and you want an index that applies the distance for you. Typesense does that with a trie, the Damerau swap rule and length-based typo limits, and ranks the results in the same request.
FAQ
What is the Levenshtein distance between kitten and sitting?
It’s 3. Substitute k with s, substitute e with i, and insert g at the end. You can check it in the calculator above.
What is the time complexity of Levenshtein distance?
Time grows with len(a) × len(b), and memory with the shorter string when you keep two rows. If you only need distances up to a limit k, filling the cells within k of the diagonal cuts the time to about k × the shorter length.
What is the difference between Levenshtein and Damerau-Levenshtein distance?
Damerau-Levenshtein adds a fourth edit, swapping two adjacent letters, at a cost of 1. So kitetn is 1 edit from kitten instead of 2. The common OSA variant, which Typesense uses, never edits a substring more than once, and unlike plain Levenshtein it isn’t a true metric.
How do I calculate a Levenshtein similarity percentage?
Subtract the distance divided by the longer length from 1. For kiten and kitten, that’s 1 - 1/6 = 0.83, or the 83.3% the calculator shows. Python’s Levenshtein.ratio gives 0.91 for the same pair, because it divides by the sum of both lengths.
Is Levenshtein distance case-sensitive?
Yes, K and k count as different letters. Lowercase both strings first if case shouldn’t matter.
Related Articles
- Fuzzy string matching in Python compares
difflib,Levenshteinand FuzzyWuzzy. - What is fuzzy search? explains typo-tolerant search.
- Fuzzy search in JavaScript with Fuse.js searches a small list in the browser.
- Typo tolerance in Elasticsearch covers the
fuzzinesssetting.