Sub topic 11
Handling Transpositions: OSA versus Damerau-Levenshtein
This chapter assumes you already know the Levenshtein recurrence, how to fill the (m+1) × (n+1) dynamic programming table, and Big-O notation. Here we add a fourth edit operation, the transposition, and look at the two common ways to include it. The two give different answers on some inputs, so the choice matters.
Why transpositions need their own operation
Typing errors often swap two neighboring characters: "teh" for "the", "form" for "from". Plain Levenshtein distance charges 2 for such a swap, because it has to do two substitutions (or a delete plus an insert):
- "ab" → "bb" (substitute) → "ba" (substitute): cost 2.
A transposition swaps two adjacent characters in one step at cost 1. Damerau observed in 1964 that most single-error misspellings are one insertion, deletion, substitution, or adjacent swap. Counting the swap as one error makes the distance better match what humans actually get wrong.
You can add the swap to the recurrence in two ways:
| Variant | Rule | Time | Extra space | Metric? | Column | Column |
|---|---|---|---|---|---|---|
| Levenshtein | insert, delete, substitute | O(mn) | none | yes | ||
| Optimal string alignment (OSA) | adds adjacent swap; no substring edited more than once | O(mn) | none | no | ||
| Damerau-Levenshtein (unrestricted) | adds adjacent swap; later edits may touch swapped characters | O(mn) | O(\ | Σ\ | ) for last-seen positions | yes |
Σ is the alphabet. Many sources and libraries call OSA "Damerau-Levenshtein", which causes confusion. Check which one a library implements before you rely on its numbers.
Optimal string alignment: one extra case
OSA keeps the Levenshtein recurrence and adds one more candidate. If the last two characters of the prefix of a are the last two characters of the prefix of b in reverse order, you can reach dp[i][j] from dp[i-2][j-2] at cost 1:
dp[i][j] = min(
dp[i-1][j] + 1, # delete
dp[i][j-1] + 1, # insert
dp[i-1][j-1] + cost, # match or substitute
dp[i-2][j-2] + 1 if i > 1, j > 1,
a[i-1] == b[j-2], a[i-2] == b[j-1]
)def osa_distance(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)
if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
dp[i][j] = min(dp[i][j], dp[i - 2][j - 2] + 1)
return dp[m][n]
assert osa_distance("ab", "ba") == 1
assert osa_distance("ca", "abc") == 3 # unrestricted Damerau-Levenshtein gives 2The swap case looks back two rows. A space-optimized version therefore needs three rows instead of two. Otherwise it is the same trick from the two-row chapter.
Where OSA falls short
Fill the OSA table for a = "ca" (rows) and b = "abc" (columns):
| Row | "" | a | b | c |
|---|---|---|---|---|
| "" | 0 | 1 | 2 | 3 |
| c | 1 | 1 | 2 | 2 |
| a | 2 | 1 | 2 | 3 |
The swap case fires only where the last two characters cross over exactly. That never happens in this table: at cell (2, 2), "ca" ends in "ca" but "ab" ends in "ab". So OSA reports 3.
A cheaper route does exist: swap "ca" → "ac" (cost 1), then insert "b" between the two characters → "abc" (cost 1), for a total of 2. OSA cannot represent this route. After the swap, the inserted "b" sits between the swapped characters. OSA treats the swapped pair as one block that nothing else can edit afterwards.
This restriction also breaks the triangle inequality: OSA("ca", "ac") = 1 and OSA("ac", "abc") = 1, yet OSA("ca", "abc") = 3 > 1 + 1. The metric-properties chapter explains why that matters. For now, remember that OSA is not a metric and that metric-tree indexes such as BK-trees can give wrong results with it.
Unrestricted Damerau-Levenshtein
To allow edits between swapped characters, the recurrence has to consider transpositions whose two characters are far apart in the prefixes, with deletions and insertions in between. Lowrance and Wagner (1975) showed you only need to check one candidate per cell:
k: the last row (1-based, beforei) wherea[k-1] == b[j-1].l: the last column (beforej) whereb[l-1] == a[i-1].
The candidate cost is d[k-1][l-1] + (i-k-1) + 1 + (j-l-1). The terms are, in order: the distance before the pair, delete the characters of a between the pair, the swap itself, and insert the characters of b between the pair. Using the most recent occurrence is enough because an earlier match would only add more deletions or insertions.
def damerau_levenshtein(a, b):
m, n = len(a), len(b)
inf = m + n # larger than any real distance
# d is shifted by one so that index 0 is a sentinel row/column.
d = [[0] * (n + 2) for _ in range(m + 2)]
d[0][0] = inf
for i in range(m + 1):
d[i + 1][0] = inf
d[i + 1][1] = i
for j in range(n + 1):
d[0][j + 1] = inf
d[1][j + 1] = j
last_row = {} # char -> last row in a where it appeared
for i in range(1, m + 1):
last_col = 0 # last column in this row where b matched a[i-1]
for j in range(1, n + 1):
k = last_row.get(b[j - 1], 0)
l = last_col
if a[i - 1] == b[j - 1]:
cost = 0
last_col = j
else:
cost = 1
d[i + 1][j + 1] = min(
d[i][j] + cost, # match / substitute
d[i + 1][j] + 1, # insert
d[i][j + 1] + 1, # delete
d[k][l] + (i - k - 1) + 1 + (j - l - 1), # transpose
)
last_row[a[i - 1]] = i
return d[m + 1][n + 1]
assert damerau_levenshtein("ca", "abc") == 2
assert damerau_levenshtein("ab", "ba") == 1
assert damerau_levenshtein("kitten", "sitting") == 3Check the "ca"/"abc" case at i = 2 (character "a") and j = 3 (character "c"). The last "c" in a is at row k = 1. The last "a" in b before column 3 is at l = 1. The candidate is d[1][1] (the shifted cell for empty-versus-empty, value 0) + 0 deletions + 1 swap + 1 insertion = 2.
Costs and gotchas
- Time is still O(mn), because each cell does constant work plus one dictionary lookup.
- Space is O(mn) for the table plus O(|Σ|) for
last_row. The two-row trick does not apply directly, becaused[k][l]can reach any earlier row. Implementations that need low memory usually fall back to OSA. - Weighted transpositions. If you give swaps their own cost, the Lowrance-Wagner argument holds only when
2 * transpose_cost >= insert_cost + delete_cost. Below that bound, the single most-recent candidate can miss the optimum. - Traceback works as before, but a transposition step jumps from
(i, j)to(k-1, l-1)and emits the deletions and insertions between the two positions. - Unicode. Python strings index by code point. A swapped pair of grapheme clusters, such as an accented letter written as base character plus combining mark, does not count as a single transposition. Normalize the strings first (for example
unicodedata.normalize("NFC", s)) if this matters to you.
Choosing between them
| Situation | Reasonable choice |
|---|---|
| Spell checking short words, single typos | OSA: simpler, three rows of memory, agrees with DL on one-error cases |
| Metric index (BK-tree, VP-tree) | Damerau-Levenshtein or plain Levenshtein, because OSA breaks the triangle inequality |
| Long sequences, tight memory | OSA or Levenshtein with row reuse |
| DNA or protein sequences | Usually plain Levenshtein or weighted alignment; adjacent swaps are not a common mutation |
| Matching another system's scores | Find out which variant it uses; many tools named "Damerau-Levenshtein" actually compute OSA |
The two variants agree whenever the best edit sequence never edits a swapped pair again. For dictionary lookups with distance 1 they always agree. Differences show up at distance 2 and above.
Exercise
Compute OSA("abc", "ca") and Damerau-Levenshtein("abc", "ca") by hand, and describe an optimal edit sequence for each.
Show answer
OSA gives 3: for example, delete "a", delete "b", insert "a" at the end ("abc" → "bc" → "c" → "ca"). Damerau-Levenshtein gives 2: delete "b" ("abc" → "ac"), then swap "a" and "c" ("ac" → "ca"). OSA forbids this route because the swap involves characters that were separated by the deleted "b", which counts as editing the substring after the transposition's characters were changed by another operation.
Exercise
Show with specific strings that OSA violates the triangle inequality, and explain why that makes it unsafe for a BK-tree.
Show answer
OSA("ca", "ac") = 1 and OSA("ac", "abc") = 1, but OSA("ca", "abc") = 3, which is greater than 1 + 1. A BK-tree skips subtrees using the bound |d(q, node) − d(node, x)| ≤ d(q, x), which follows from the triangle inequality. With OSA, that bound can be wrong, so the search may skip a subtree that holds a true match.
Exercise
Modify osa_distance to use only three rows of memory, and explain why two rows are not enough.
Show answer
Keep rows prev2, prev, and curr. Compute curr[j] from prev[j] + 1, curr[j-1] + 1, prev[j-1] + cost, and, when the swap condition holds, prev2[j-2] + 1. At the end of each row, shift: prev2, prev = prev, curr. Two rows are not enough because the transposition case reads dp[i-2][j-2], which lives two rows back.