Implementing a Damerau-Levenshtein Distance Function in KQL
In our previous blog post, Implementing a Levenshtein Distance Function in KQL, we went through the Levenshtein Distance algorithm, explained how it works, and provided an implementation of the algorithm as a function in KQL.
While the Levenshtein distance is useful for measuring string similarity, a later variation of the algorithm is better suited to our needs.
Damerau-Levenshtein vs Levenshtein
The Damerau-Levenshtein Distance was introduced by a computer scientist named Frederick J. Damerau in 1964 as an extension of the classic Levenshtein Distance algorithm. The algorithm was developed to address common spelling errors, particularly those caused by accidentally swapping two adjacent characters.
Consider the following example: comparing the strings form and from. The two strings contain exactly the same characters, but the adjacent characters o and r have swapped positions. Using the standard Levenshtein distance, we need 2 edit operations to transform form into from:
- Delete the character o: form → frm
- Insert o after r: frm → from
Therefore, the Levenshtein distance is 2.
The Damerau-Levenshtein distance, on the other hand, extends the original algorithm by introducing an additional edit operation: the transposition of two adjacent characters, allowing the swapping of o and r as a single operation. Consequently, the Damerau-Levenshtein distance between the two strings is 1.
Optimal String Alignment (OSA) vs Unrestricted Damerau-Levenshtein
The Damerau-Levenshtein distance has two main variations: Optimal String Alignment (OSA) and Unrestricted Damerau-Levenshtein. Both measure the minimum number of edits required to transform one string into another, allowing insertions, deletions, substitutions, and transpositions of adjacent characters. However, OSA restricts each substring to being edited only once, which can produce a higher distance in certain cases.
In contrast, unrestricted Damerau-Levenshtein allows edits to be applied without this restriction, producing the true minimum edit distance. The Lowrance-Wagner algorithm (1975) provides an efficient way of calculating the unrestricted Damerau-Levenshtein distance by keeping track of the last occurrences of characters in both strings, allowing it to correctly calculate transpositions even when other edit operations have occurred between them. This additional tracking enables it to consider all valid sequences of insertions, deletions, substitutions, and adjacent transpositions, without the restriction that a substring can only be edited once.
To demonstrate the difference between those two algorithms consider the following example. Suppose that we want to compare the string CA with the string ABC. Let’s see how this would be performed using the two different implementations.
Unrestricted Damerau-Levenshtein:
The unrestricted Damerau-Levenshtein algorithm allows characters or substrings to be involved in multiple edit operations so we can do the following:
- Transpose the adjacent characters: CA → AC
- Insert B between A and C: AC → ABC
Therefore, the unrestricted Damerau-Levenshtein distance is 2.
Optimal String Alignment (OSA) Distance:
The OSA algorithm does not allow the same substring to be edited more than once. In our example, although we can initially transpose CA into AC, we cannot then insert B to obtain ABC, because this would involve editing a substring that has already been modified by the transposition. Consequently, we need three operations:
- Delete C: CA → A
- Insert B: A → AB
- Insert C: AB → ABC
Therefore, the OSA distance is 3.
So why does the difference between those two variations matter, you may ask? Well, in mathematics there is something called the triangle inequality, which states that the direct distance between two points cannot be greater than the sum of the distances through an intermediate point.
In other words, transforming A into C directly should never require more operations than transforming A into B and then B into C.
Applying this principle to our example above for transforming CA to ABC, we would expect the following inequality to be true:
OSA(CA, ABC) ≤ OSA(CA, AC) + OSA(AC, ABC)
But when using the OSA distance:
- OSA(CA, AC) = 1 (transpose C and A)
- OSA(AC, ABC) = 1 (insert B)
- OSA(CA, ABC) = 3 (delete C: CA → A, insert B: A → AB, insert C: AB → ABC)
The calculation gives us 3 > 1 + 1, violating the triangle inequality. This is why OSA is not considered a true distance metric, unlike the unrestricted Damerau-Levenshtein distance, which satisfies the triangle inequality. That said, OSA is considerably simpler to implement than the unrestricted Damerau-Levenshtein algorithm.
But does this distinction ultimately matter for our goal of using the algorithm to detect typosquatting attacks? In my opinion, not particularly. What we really need is a way to quantify how similar or different two strings are. In most detection engineering scenarios, we’re primarily interested in identifying strings that are only slightly different from one another. We can also use configurable distance thresholds to control how sensitive our queries are, adjusting how much variation we’re willing to tolerate when identifying potential matches.
Nevertheless, for the sake of completeness, I thought it was worth exploring the differences between the two variations before moving on to their actual implementations in KQL.
The Optimal String Alignment (OSA) Algorithm
For the OSA implementation, the matrix calculation is very similar to the Levenshtein calculation described in our previous blog post. The main difference is that, for each cell, the cost calculation also considers transposition as a possible operation. When two adjacent characters can be swapped, the algorithm considers the cost from the cell two positions diagonally above and to the left, plus one.
Why two positions diagonally? Consider the following example comparing the strings form with from. We have already processed the characters fo in the first string and fr in the second one. The next characters are r in the first string and o in the second one, which can be swapped because the preceding characters are o in the first string and r in the second. Therefore, we look back two positions in both dimensions (i-2, j-2) to the point before those characters were processed, and add 1 for the transposition operation. In other words, the diagonal offset of two reflects the fact that a transposition accounts for two characters in each string but costs only one edit operation.
"" f r o m
+----------------
"" | 0 1 2 3 4
f | 1 0 1 2 3
o | 2 1 1 1 2
r | 3 2 1 1 2
m | 4 3 2 2 1In this case the cost for the transposition is 0+1=1. This additional cost is included alongside the insertion, deletion, and substitution costs, and the minimum of all four is selected.

OSA Distance cost calculation
As a reminder, for the substitution operation c=0 if the characters being compared are identical, and c=1 otherwise.
The Optimal String Alignment (OSA) KQL Function
Now let’s look at the KQL implementation.
let DamerauLevenshteinOSADistance = (tbl:(*), ColumnA:string, ColumnB:string) {
let T = materialize(
tbl
| extend
WordA = tostring(column_ifexists(ColumnA, "")),
WordB = tostring(column_ifexists(ColumnB, ""))
| summarize by WordA, WordB
);
T
| serialize
| extend _id = row_number()
| extend LengthA = strlen(WordA)
| extend LengthB = strlen(WordB)
| mv-expand i = range(0, LengthA) to typeof(long)
| mv-expand j = range(0, LengthB) to typeof(long)
| sort by _id asc, i asc, j asc
| scan declare (
osa_matrix:dynamic = dynamic({})
)
with (
step s: true =>
osa_matrix = bag_set_key(
iff(i == 0 and j == 0, dynamic({}), s.osa_matrix),
strcat(i, "_", j),
case(
i == 0, j,
j == 0, i,
min_of(
tolong(s.osa_matrix[strcat(i - 1, "_", j)]) + 1,
tolong(s.osa_matrix[strcat(i, "_", j - 1)]) + 1,
tolong(s.osa_matrix[strcat(i - 1, "_", j - 1)])
+ iff(
substring(WordA, i - 1, 1)
== substring(WordB, j - 1, 1),
0,
1
),
iff(
i > 1 and j > 1
and substring(WordA, i - 1, 1)
== substring(WordB, j - 2, 1)
and substring(WordA, i - 2, 1)
== substring(WordB, j - 1, 1),
tolong(s.osa_matrix[strcat(i - 2, "_", j - 2)]) + 1,
long(null)
)
)
)
);
)
| where i == LengthA and j == LengthB
| extend Distance = tolong(osa_matrix[strcat(LengthA, "_", LengthB)])
| project
WordA,
WordB,
Distance
};The only difference between the Levenshtein implementation and OSA is the inclusion of the iff() condition inside the min_of(). The iff() checks whether a transposition is possible for the current pair of characters. If it is, it calculates the transposition cost. Otherwise, it returns long(null), indicating that a transposition is not a valid operation at that position.
iff(
i > 1 and j > 1
and substring(WordA, i - 1, 1)
== substring(WordB, j - 2, 1)
and substring(WordA, i - 2, 1)
== substring(WordB, j - 1, 1),
tolong(s.osa_matrix[strcat(i - 2, "_", j - 2)]) + 1,
long(null)
)The long(null) is ignored by the min_of() evaluation because min_of() gives precedence to non-null values against null ones. This means that when a transposition is not possible, min_of() selects the minimum cost of the remaining 3 operations (insertion, deletion, substitution). In other words, returning long(null) effectively excludes the transposition cost from the minimum calculation when the required conditions are not met. To showcase how this is evaluated by KQL take a look at the following screenshot.

min_of evaluation of a number and a long(null)
The Unrestricted Damerau-Levenshtein Algorithm
The Unrestricted Damerau-Levenshtein is significantly more complex to explain than OSA or standard Levenshtein. What differentiates it from OSA is that it allows for the same characters to participate in multiple editing operations. This means that a character can be inserted, deleted, substituted or transposed as part of a sequence of operations. For example, characters that are not adjacent in the original strings can become adjacent through deletions and then be transposed. Similarly, two characters can be transposed and have other characters inserted between them afterwards.
Consider the following two scenarios:
- Transposition followed by insertion: AB → BA → BXA. The characters A and B are transposed, and X is subsequently inserted between them.
- Deletion followed by transposition: ACB → AB → BA. The character C is deleted, making A and B adjacent, allowing them to be transposed.
The challenge with unrestricted transpositions is that the two characters being swapped don’t necessarily appear next to each other in the original strings. They may be separated by other characters, which means the algorithm needs to look back through previously processed characters to identify potential transpositions. A simplistic approach would involve repeatedly searching backwards through the strings to find the relevant character positions every time a transposition is considered. This is computationally expensive. Lowrance and Wagner addressed this by maintaining a record of the last occurrence of each character in the source string (let’s call that DA), along with the last matching position in the target string (let’s call that DB) while processing each row of the distance matrix. Instead of repeatedly searching through the strings, the algorithm can retrieve these positions directly and use them to calculate the cost of a transposition.
Consider the following example, where we want to compare the word LETTER (source) and the word TELLER (target).
As the algorithm processes the source word, it maintains a dictionary (DA), which records the most recent position of each character encountered. The dictionary is updated after processing each character:
- L: {L: 1}
- E: {L: 1, E: 2}
- T: {L: 1, E: 2, T: 3}
- T: {L: 1, E: 2, T: 4} ← Notice the update of the T index.
- E: {L: 1, E: 5, T: 4} ← Notice the update of the E index.
- R: {L: 1, E: 5, T: 4, R: 6}
As you can see, whenever a repeated character is encountered, its previous position is overwritten with its latest position.
Unlike DA, which keeps track of the last occurrence of every character in the source word, DB records the last position in the target word where the current source character was found. For example, when processing the second E in LETTER (position 5), the algorithm scans the target word, TELLER, from left to right and updates DB whenever it finds a match.
- T: 0
- E: 2 ← Notice the update of DB as the character E is encountered.
- L: 2
- L: 2
- E: 5 ← Notice the update of DB as the character E is encountered again.
- R: 5
Initially, DB is 0 because no matching character has been found yet. When the algorithm encounters the first E at position 2, DB is updated to 2. When it encounters the second E at position 5, the value is updated again to 5.
When the algorithm encounters a mismatch (source word character != target word character), it uses DA and DB to identify a potential transposition:
- DA identifies the previous source position of the target character.
- DB identifies the previous target position of the current source character.
The algorithm can then calculate the cost of transposing them, including any intervening insertions and deletions. The transposition cost is calculated by looking at the distance before the two characters being transposed, plus the edits needed to get from those characters to the current positions.

Transposition cost for Unrestricted Damerau-Levenshtein
- i = current position in the source word.
- j = current position in the target word.
- k = previous position of the target character in the source word, obtained from DA.
- l = previous position of the current source character in the target word, obtained from DB.
- H[k-1, l-1] = edit distance before the two characters involved in the transposition.
- i-k-1 = number of characters between the two positions in the source word (deletions).
- 1 = cost of the transposition.
- j-l-1 = number of characters between the two positions in the target word (insertions).
That transposition cost is also evaluated against the insertion, deletion and substitution costs.

Unrestricted Damerau-Levenshtein Distance cost calculation
The Unrestricted Damerau-Levenshtein KQL Function
Now that the technicalities of the algorithm are out of the way, let’s move on to the function implementation.
let DamerauLevenshteinUnrestricted = (tbl: (*), ColumnA: string, ColumnB: string) {
let T = materialize(
tbl
| extend
WordA = tostring(column_ifexists(ColumnA, "")),
WordB = tostring(column_ifexists(ColumnB, ""))
| summarize by WordA, WordB
);
T
| serialize
| extend _id = row_number()
| extend LengthA = strlen(WordA)
| extend LengthB = strlen(WordB)
| mv-expand i = range(0, LengthA) to typeof(long)
| mv-expand j = range(0, LengthB) to typeof(long)
| sort by _id asc, i asc, j asc
| scan declare (
dl_matrix: dynamic = dynamic({}),
da: dynamic = dynamic({}),
db: long = 0
)
with (
step s: true =>
dl_matrix = bag_set_key(
iff(i == 0 and j == 0, dynamic({}), s.dl_matrix),
strcat(i, "_", j),
case(
i == 0, j,
j == 0, i,
min_of(
tolong(s.dl_matrix[strcat(i - 1, "_", j)]) + 1,
tolong(s.dl_matrix[strcat(i, "_", j - 1)]) + 1,
tolong(s.dl_matrix[strcat(i - 1, "_", j - 1)])
+ iff(
substring(WordA, i - 1, 1)
== substring(WordB, j - 1, 1),
0,
1
),
iff(
coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0) > 0 and s.db > 0,
tolong(
s.dl_matrix[strcat(
coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0) - 1,
"_",
s.db - 1
)]
)
+ (i - coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0) - 1)
+ 1
+ (j - s.db - 1),
long(null)
)
)
)
),
db = iff(
j == 0,
0,
iff(
i >= 1 and substring(WordA, i - 1, 1) == substring(WordB, j - 1, 1),
j,
s.db
)
),
da = iff(
i == 0 and j == 0,
dynamic({}),
iff(
j == LengthB and i >= 1,
bag_set_key(s.da, substring(WordA, i - 1, 1), i),
s.da
)
);
)
| where i == LengthA and j == LengthB
| extend Distance = tolong(dl_matrix[strcat(LengthA, "_", LengthB)])
| project
WordA,
WordB,
Distance
};We are going to focus on providing a bit more explanation of the implementation differences between this algorithm and the original Levenshtein function.
We use scan to declare and initialize three variables that maintain the state of the algorithm as we iterate through the matrix. dl_matrix is a dynamic object that stores the calculated edit distances for each matrix cell. da keeps track of the last row in which each character of WordA was encountered, while db stores the last matching column position of a character in WordA during the current row.
| scan declare (
dl_matrix: dynamic = dynamic({}),
da: dynamic = dynamic({}),
db: long = 0
)The insertion, deletion and substitution operations are calculated exactly the same. But for the transposition operation we use the following to calculate the cost in accordance to the cost calculation formula of the algorithm.
iff(
coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0) > 0 and s.db > 0,
tolong(
s.dl_matrix[strcat(
coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0) - 1,
"_",
s.db - 1
)]
)
+ (i - coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0) - 1)
+ 1
+ (j - s.db - 1),
long(null)
)The transposition calculation is performed only when the current character in WordB has previously appeared in WordA, and the current character in WordA has previously appeared in WordB. If either character has no previous occurrence, the transposition calculation returns long(null), which is ignored by the min_of() operator, allowing the algorithm to select the minimum valid cost among the remaining operations.
However, if both characters have previous occurrences, the algorithm calculates the transposition cost using the formula we showed before.

Transposition cost for Unrestricted Damerau-Levenshtein
To break this down and make the calculation easier to understand, let’s examine each part individually:
- k →
coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0): Represents the last known position of the current character inWordBwithinWordA. Thesubstring()extracts the current character fromWordB,s.da[...]looks up its last recorded position inWordA,tolong()converts the position to a long integer, andcoalesce(..., 0)returns0if no previous occurrence exists. - l →
s.db: Represents the last known position of the current character inWordAwithinWordB. The variable tracks the position where the current character fromWordAwas last encountered inWordB. If no previous occurrence exists, its value remains0. - D[k-1, l-1] →
tolong(s.dl_matrix[strcat(coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0) - 1, "_", s.db - 1)]) - (i-k-1) →
(i - coalesce(tolong(s.da[substring(WordB, j - 1, 1)]), 0) - 1) - +1 →
+1: Represents the transposition operation itself, with a cost of one. - (j-l-1) →
(j - s.db - 1)
Next comes the update of the db variable. It is reset to 0 when j == 0. Otherwise, if the current characters in WordA and WordB match, db is updated to the current position j. If they do not match, the previous value (s.db) is retained.
db = iff(
j == 0,
0,
iff(
i >= 1 and substring(WordA, i - 1, 1) == substring(WordB, j - 1, 1),
j,
s.db
)
)Finally, the da variable is initialized as an empty dynamic object when i == 0 and j == 0, indicating that a new pair of words is being analyzed. Once the algorithm reaches the last column (j == LengthB), bag_set_key() updates the position of the current character from WordA, storing the character as the key and its position i as the value. Otherwise, the previous value s.da is retained.
da = iff(
i == 0 and j == 0,
dynamic({}),
iff(
j == LengthB and i >= 1,
bag_set_key(s.da, substring(WordA, i - 1, 1), i),
s.da
)
)
da and db being populated and reset as the algorithm progresses
Sanity Checks
We once again want to validate our KQL function by comparing its results against independent implementations of the Optimal String Alignment (OSA) and unrestricted Damerau–Levenshtein algorithms provided by the Python RapidFuzz package.
"""Install: pip install rapidfuzz
Distance = Damerau-Levenshtein OSA (restricted)
Distance1 = Damerau-Levenshtein unrestricted"""
from rapidfuzz.distance import DamerauLevenshtein, OSA
WORD_A = "act"
VARIATIONS = [
"chat", "coat", "cheat", "clean", "clear",
"cheap", "clap", "clay", "clad", "crab",
]
def main() -> None:
print(f"{'WordA':<8}{'WordB':<10}{'Distance':>11}{'Distance1':>11}")
for word_b in VARIATIONS:
print(
f"{WORD_A:<8}{word_b:<10}"
f"{OSA.distance(WORD_A, word_b):>11}"
f"{DamerauLevenshtein.distance(WORD_A, word_b):>11}"
)
if __name__ == "__main__":
main()
OSA (Distance) and unrestricted Damerau–Levenshtein (Distance1) distance calculations using our python script.
The distance calculations match those produced by our KQL function for the test dataset.
let TestWords = datatable(Variation:string)
[
"chat",
"coat",
"cheat",
"clean",
"clear",
"cheap",
"clap",
"clay",
"clad",
"crab"
];
TestWords
| extend Original = "act"
| invoke DamerauLevenshteinOSADistance(ColumnA="Original", ColumnB="Variation")
| join kind = inner (
TestWords
| extend Original = "act"
| invoke DamerauLevenshteinUnrestricted(ColumnA="Original", ColumnB="Variation")
) on $left.WordA == $right.WordA and $left.WordB == $right.WordB
| project WordA, WordB, Distance, Distance1
OSA (Distance) and unrestricted Damerau–Levenshtein (Distance1) distance calculations using our KQL function on a test dataset.
Limitations and Considerations
We are concluding this blog post once again with a few considerations and limitations of the above implementations.
- Case sensitivity and normalization: Both functions compare the input strings exactly as provided, without applying any normalization. Consequently, comparisons are case-sensitive, and differences in capitalization or whitespace (leading, trailing, or internal) contribute to the calculated distance. If you want to ignore these differences, normalize the input strings before invoking the function.
- Choosing between OSA and unrestricted Damerau–Levenshtein: OSA is simpler to implement and understand and is sufficient for many typo-detection scenarios. Unrestricted Damerau–Levenshtein supports more complex sequences of edit operations and satisfies the triangle inequality, making it a true distance metric. The choice ultimately depends on your use case and preference. For our needs in detection engineering, either implementation should be sufficient. Both can help identify subtle differences between names and detect potential typosquatting attempts. We can also tune the distance threshold to make detections more or less sensitive, depending on how closely names need to match to trigger an alert.
Closing Thoughts
In this blog post, we went over the two variations of the Damerau–Levenshtein algorithm, Optimal String Alignment (OSA) and unrestricted Damerau–Levenshtein, and implemented both directly in KQL. We also validated our implementations against the corresponding algorithms provided by the Python RapidFuzz package to verify their results.
Now that we have our KQL functions in place, the next step is to put them to practical use. In the next blog post, we’ll explore how to leverage string similarity and the Damerau–Levenshtein distance to identify potential typosquatting or masquerading attacks, detecting domains and filenames that closely resemble legitimate ones and may be used for impersonation.