Levenshtein Distance
Algorithm Efficiency
Computational Complexity
String Matching
Computer Science

Levenshtein Distance Algorithm better than Onm?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

The classic Levenshtein distance algorithm uses dynamic programming in O(nm) time, and that is still the standard exact worst-case bound for general strings. There are faster approaches in special cases, but if you want the exact distance for arbitrary strings with no extra assumptions, there is no simple general-purpose algorithm that beats the quadratic dynamic program across the board.

The classic algorithm and what can be improved

For strings of lengths n and m, the textbook algorithm fills an (n + 1) x (m + 1) table. That gives:

  • time: O(nm)
  • space: O(nm)

Space is the first thing you can improve easily. You only need the previous row to compute the current row, so exact Levenshtein distance can be computed in O(min(n, m)) space while keeping the same O(nm) time.

python
1def levenshtein(a, b):
2    if len(a) < len(b):
3        a, b = b, a
4
5    previous = list(range(len(b) + 1))
6
7    for i, ca in enumerate(a, start=1):
8        current = [i]
9        for j, cb in enumerate(b, start=1):
10            insert_cost = current[j - 1] + 1
11            delete_cost = previous[j] + 1
12            replace_cost = previous[j - 1] + (ca != cb)
13            current.append(min(insert_cost, delete_cost, replace_cost))
14        previous = current
15
16    return previous[-1]
17
18print(levenshtein("kitten", "sitting"))

This is a useful optimization, but it does not improve time complexity.

Better than O(nm) when the edit distance is small

If you only care whether the edit distance is at most k, or you know in advance that the strings are similar, banded algorithms such as Ukkonen's method can do much better in practice. They compute only a diagonal band of the table instead of the whole matrix.

A thresholded version can stop early when the strings are too different:

python
1def levenshtein_at_most_k(a, b, k):
2    if abs(len(a) - len(b)) > k:
3        return k + 1
4
5    if len(a) < len(b):
6        a, b = b, a
7
8    previous = {j: j for j in range(min(len(b), k) + 1)}
9
10    for i, ca in enumerate(a, start=1):
11        current = {}
12        start = max(0, i - k)
13        end = min(len(b), i + k)
14
15        if start == 0:
16            current[0] = i
17
18        for j in range(max(1, start), end + 1):
19            insert_cost = current.get(j - 1, k + 1) + 1
20            delete_cost = previous.get(j, k + 1) + 1
21            replace_cost = previous.get(j - 1, k + 1) + (ca != b[j - 1])
22            current[j] = min(insert_cost, delete_cost, replace_cost)
23
24        previous = {j: d for j, d in current.items() if d <= k}
25        if not previous:
26            return k + 1
27
28    return previous.get(len(b), k + 1)
29
30print(levenshtein_at_most_k("kitten", "sitting", 3))
31print(levenshtein_at_most_k("kitten", "abcdefgh", 3))

When the true edit distance is small, this can behave more like O(k * min(n, m)) than O(nm).

Other special-case improvements

There are also faster techniques for particular settings:

  • Myers bit-parallel algorithm can speed up edit distance using machine-word operations.
  • Filtering with q-grams or tries can avoid running exact distance against every candidate in large search problems.
  • Domain-specific constraints, such as bounded maximum edits, often enable early pruning.

These methods are very valuable in search systems, spell-checkers, and approximate matching pipelines, but they are not a magic universal replacement for the quadratic dynamic program.

The important theoretical caveat

For general exact edit distance on unrestricted strings, algorithm designers do not currently have a broadly used exact worst-case algorithm that is strongly subquadratic in the input lengths. In practical terms, the question "is there something strictly better than O(nm)?" usually has this answer:

  1. Not as a general exact worst-case replacement everyone uses.
  2. Yes, if your inputs or requirements have structure you can exploit.

That distinction matters. Many engineering problems do have exploitable structure, so "quadratic in theory" does not always mean "quadratic in practice".

Common Pitfalls

The biggest mistake is assuming that a lower-space implementation is also a lower-time implementation. Using two rows instead of a full matrix improves memory, not time.

Another issue is applying a thresholded or banded algorithm when you actually need the full exact distance for very dissimilar strings. In that case the optimization may not help much.

Developers also sometimes benchmark on tiny strings and conclude the advanced algorithm is faster. Constant factors and Python overhead can dominate small cases, so test on realistic workloads.

Finally, remember the real application. If you are searching a dictionary, filtering candidates before exact edit distance often matters more than shaving a constant factor off the distance routine itself.

Summary

  • The classic exact Levenshtein algorithm is O(nm) time.
  • You can reduce memory to O(min(n, m)) without changing that time bound.
  • If the edit distance is known to be small, banded methods such as Ukkonen's can be much faster.
  • Specialized algorithms such as bit-parallel methods help in the right settings.
  • For general exact worst-case edit distance, there is no simple universal replacement that makes the classic quadratic bound irrelevant.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.