{
  "id": "damerau-levenshtein-distance",
  "title": "Damerau–Levenshtein Distance",
  "lang": "en",
  "source_lang": "en",
  "summary": "Damerau–Levenshtein distance measures the minimum number of insertions, deletions, substitutions, and adjacent transpositions needed to transform one string into another.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "Damerau–Levenshtein edit distance",
    "unrestricted Damerau–Levenshtein distance"
  ],
  "generated_at": "2026-11-05",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/damerau-levenshtein-distance/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/damerau-levenshtein-distance/",
      "json": "https://aiwiki.page/zh/damerau-levenshtein-distance.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Damerau–Levenshtein distance is an edit distance between two strings: the smallest number of single-symbol insertions, deletions, substitutions, and transpositions of adjacent symbols required to transform one string into the other. In its standard form, each operation costs one. It extends Levenshtein distance by treating an adjacent swap as one edit rather than two, making it useful for comparing strings affected by typing errors. The unrestricted distance must be distinguished from optimal string alignment distance, a simpler, restricted variant that is sometimes given the same name in software."
    },
    {
      "heading": "Definition and elementary operations",
      "text": "Let \\(x=x_1x_2\\cdots x_m\\) and \\(y=y_1y_2\\cdots y_n\\) be finite strings over an alphabet \\(\\Sigma\\). Their Damerau–Levenshtein distance, written \\(d_{\\mathrm{DL}}(x,y)\\), is the minimum length of an edit sequence converting \\(x\\) into \\(y\\), using four operations:\n\nOperation | Description | Example\nInsertion | Add one symbol | cat → cart\nDeletion | Remove one symbol | cart → cat\nSubstitution | Replace one symbol with another | cat → cut\nAdjacent transposition | Exchange two neighboring symbols | form → from\n\nA transposition exchanges neighboring symbols only; exchanging arbitrarily distant symbols is not a single operation.\n\nFor example,\n\n\\[d_{\\mathrm{DL}}(\\texttt{form},\\texttt{from})=1,\\]\n\nwhereas the Levenshtein distance between those strings is two.\n\nThe definition applies to sequences generally, not just written words. Symbols may be characters, tokens, or other discrete units, provided that equality and the allowed operations are defined consistently."
    },
    {
      "heading": "Mathematical properties",
      "text": "With unit operation costs, unrestricted Damerau–Levenshtein distance is a metric on the set of finite strings. It satisfies:\n\n- Nonnegativity: \\(d(x,y)\\geq 0\\).\n- Identity of indiscernibles: \\(d(x,y)=0\\) exactly when \\(x=y\\).\n- Symmetry: \\(d(x,y)=d(y,x)\\).\n- Triangle inequality: \\(d(x,z)\\leq d(x,y)+d(y,z)\\).\n\nSymmetry follows because every allowed operation has an inverse of equal cost. The triangle inequality follows because a sequence transforming \\(x\\) into \\(y\\) can be followed by one transforming \\(y\\) into \\(z\\).\n\nFor strings of lengths \\(m\\) and \\(n\\),\n\n\\[|m-n|\\leq d_{\\mathrm{DL}}(x,y)\\leq \\max(m,n).\\]\n\nThe lower bound follows because only insertion and deletion change length, each by one. For the upper bound, corresponding symbols can be substituted and any remaining symbols inserted or deleted.\n\nThe relationship to Levenshtein distance is\n\n\\[d_{\\mathrm{DL}}(x,y)\\leq d_{\\mathrm{Lev}}(x,y),\\]\n\nbecause every Levenshtein edit sequence is also permitted under Damerau–Levenshtein distance. Unlike Hamming distance, which counts position-wise mismatches between equal-length sequences, both distances allow insertions and deletions."
    },
    {
      "heading": "Unrestricted distance and optimal string alignment",
      "text": "An important distinction concerns whether edits may interact with parts of a string that have already been edited.\n\nUnrestricted Damerau–Levenshtein distance permits arbitrary sequences of the four elementary operations. Optimal string alignment distance, or OSA distance, restricts how edited substrings can be reused. Its usual dynamic-programming recurrence adds only a local adjacent-transposition case to the Levenshtein recurrence. That modification does not compute the unrestricted distance in every case.\n\nA standard example is\n\n\\[\\texttt{CA}\\rightarrow\\texttt{AC}\\rightarrow\\texttt{ABC}.\\]\n\nThe first operation transposes C and A; the second inserts B between them. Consequently,\n\n\\[d_{\\mathrm{DL}}(\\texttt{CA},\\texttt{ABC})=2.\\]\n\nOSA distance assigns three to this pair. Its restrictions do not capture that two-operation sequence.\n\nThis difference also means that OSA distance does not satisfy the triangle inequality:\n\n\\[d_{\\mathrm{OSA}}(\\texttt{CA},\\texttt{ABC})=3,\\]\n\nbut\n\n\\[d_{\\mathrm{OSA}}(\\texttt{CA},\\texttt{AC}) + d_{\\mathrm{OSA}}(\\texttt{AC},\\texttt{ABC}) =1+1=2.\\]\n\nThe distinction matters when an algorithm relies on metric properties for pruning or indexing. A software interface labeled “Damerau–Levenshtein” may implement either variant."
    },
    {
      "heading": "Dynamic-programming computation",
      "text": "Both variants can be computed by dynamic programming, but they require different recurrences.\n\nRestricted recurrence\n\nLet \\(R_{i,j}\\) denote the OSA distance between the first \\(i\\) symbols of \\(x\\) and the first \\(j\\) symbols of \\(y\\). Initialize\n\n\\[R_{i,0}=i,\\qquad R_{0,j}=j.\\]\n\nDefine the substitution cost\n\n\\[c_{i,j}= \\begin{cases} 0,&x_i=y_j,\\\\ 1,&x_i\\ne y_j. \\end{cases}\\]\n\nThe usual three candidates are\n\n\\[R_{i,j}= \\min\\left\\{ R_{i-1,j}+1,\\; R_{i,j-1}+1,\\; R_{i-1,j-1}+c_{i,j} \\right\\}.\\]\n\nIf \\(i,j\\geq2\\), \\(x_i=y_{j-1}\\), and \\(x_{i-1}=y_j\\), the additional transposition candidate is\n\n\\[R_{i-2,j-2}+1.\\]\n\nThis recurrence is compact, but its transposition case considers only the two immediately preceding symbols.\n\nUnrestricted recurrence\n\nFor unrestricted distance, the computation must account for transpositions whose endpoints are separated by symbols deleted from the source or inserted into the target.\n\nLet \\(D_{i,j}\\) be the unrestricted distance between prefixes of lengths \\(i\\) and \\(j\\), with\n\n\\[D_{i,0}=i,\\qquad D_{0,j}=j.\\]\n\nAt cell \\((i,j)\\), let:\n\n- \\(k\\) be the greatest index less than \\(i\\) for which \\(x_k=y_j\\);\n- \\(\\ell\\) be the greatest index less than \\(j\\) for which \\(y_\\ell=x_i\\).\n\nAlongside the insertion, deletion, and substitution candidates, consider\n\n\\[D_{k-1,\\ell-1} +(i-k-1) +1 +(j-\\ell-1).\\]\n\nThis candidate is omitted if either earlier occurrence does not exist. Its terms represent transforming the preceding prefixes, deleting intervening source symbols, transposing the matched endpoints, and inserting intervening target symbols.\n\nThus,\n\n\\[D_{i,j}= \\min\\left\\{ \\begin{aligned} &D_{i-1,j}+1,\\\\ &D_{i,j-1}+1,\\\\ &D_{i-1,j-1}+c_{i,j},\\\\ &D_{k-1,\\ell-1}+(i-k-1)+1+(j-\\ell-1) \\end{aligned} \\right\\},\\]\n\nwith the final candidate included only when applicable.\n\nAn implementation can maintain last-occurrence information in an array or hash table, rather than repeatedly scanning prefixes.\n\nComputational cost\n\nFor lengths \\(m\\) and \\(n\\), standard implementations have \\(O(mn)\\) time complexity. A full dynamic-programming table uses \\(O(mn)\\) space; unrestricted computation also maintains occurrence information.\n\nOSA distance alone can be computed with three rolling rows, reducing auxiliary storage to \\(O(\\min(m,n))\\). The same simple rolling-row technique does not directly apply to the unrestricted recurrence, whose transposition candidate can refer to much earlier rows.\n\nRecovering an actual sequence of edits requires traceback information or another reconstruction method. Computing only the numerical distance does not automatically provide an alignment."
    },
    {
      "heading": "Historical development",
      "text": "The name combines the work of Frederick J. Damerau and Vladimir I. Levenshtein. Damerau’s 1964 work on detecting and correcting spelling errors treated insertion, deletion, substitution, and adjacent transposition as important elementary error types. Levenshtein’s work in the 1960s established foundational results on distances involving deletions, insertions, and substitutions.\n\nLater algorithmic work developed efficient methods for handling transpositions. Roy Lowrance and Robert A. Wagner published an influential algorithm for an extended string-correction problem in 1975. The historical relationship between spelling-error models and string-correction algorithms helps explain why restricted and unrestricted variants are sometimes conflated."
    },
    {
      "heading": "Applications and limitations",
      "text": "Damerau–Levenshtein distance is used in approximate string matching, spelling correction, information retrieval, and record matching. Adjacent transpositions make it particularly relevant to errors such as teh for the.\n\nIn natural language processing, it can supply a similarity feature or help generate candidate corrections. It does not, by itself, identify the most likely intended word: frequency, context, pronunciation, and keyboard layout can all distinguish candidates at the same edit distance.\n\nSeveral modeling choices affect its interpretation:\n\n- Text representation: A Unicode string can be compared as bytes, code points, or grapheme clusters. These units can produce different distances.\n- Preprocessing: Case folding, punctuation removal, or Unicode normalization changes which distinctions the comparison preserves.\n- Operation costs: Unit costs treat all substitutions and adjacent swaps equally. Weighted models can express different error likelihoods, but metric properties depend on the cost rules.\n- Length normalization: Dividing by a length-based denominator can facilitate comparisons across different string lengths, but the resulting score is not automatically a metric.\n- Meaning: Small character-level distance does not imply semantic similarity, and semantically equivalent expressions can have a large distance.\n\nFor long sequences or large collections, quadratic pairwise comparison can be expensive. Practical systems often combine edit-distance computation with candidate filtering, indexing, length bounds, or a maximum permitted distance."
    }
  ],
  "links": [
    "edit-distance",
    "metric-space",
    "hamming-distance",
    "algorithm",
    "dynamic-programming",
    "hash-table",
    "time-complexity",
    "space-complexity",
    "information-retrieval",
    "natural-language-processing",
    "unicode",
    "code-point",
    "grapheme-cluster"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}