Levenshtein distance how to better handle words swapping positions?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Levenshtein distance is a popular string metric used in computer science and information theory to quantify the difference between two sequences. It calculates the minimum number of single-character edits—insertions, deletions, or substitutions—required to change one word into the other. However, one limitation of the traditional Levenshtein distance algorithm is its inability to handle situations where words swap positions meaningfully. This article delves into how one might address this limitation while keeping a focus on Levenshtein distance.
Basic Understanding of Levenshtein Distance
The Levenshtein distance between two strings a
and b
, denoted lev(a, b)
, is calculated using a dynamic programming approach. Here is a pseudocode representation of the algorithm:
- Initialize a matrix
dwith dimensions(length(a)+1) x (length(b)+1). - Set
d[i][0] = iandd[0][j] = jfor alliandj. - For each
ifrom 1 tolength(a):- For each
jfrom 1 tolength(b):- If
a[i-1] == b[j-1], cost = 0; else cost = 1. - Set
d[i][j] = min(d[i-1][j] + 1, d[i][j-1] + 1, d[i-1][j-1] + cost).
- Return
d[length(a)][length(b)].
Example: Calculating Levenshtein Distance
Consider the words "kitten" and "sitting":
kitten -> sitten(substitution of 'k' with 's')sitten -> sittin(substitution of 'e' with 'i')sittin -> sitting(insertion of 'g')
Thus, lev(kitten, sitting) = 3
.
Handling Word Swaps
The above approach does not account for swapping of positions, as swapping a word pair involves multiple edits under the standard Levenshtein metric. To tackle this, extended or modified versions of Levenshtein distance can be introduced:
1. Damerau-Levenshtein Distance
This metric considers adjacent transpositions as a single operation. The incorporation of transpositions makes the algorithm slightly more complex but far more suited for handling position swaps:
- Extend the pseudocode to include a check for adjacent transposition:
- If
a[i] == b[j-1]anda[i-1] == b[j]then considerd[i][j] = d[i-2][j-2] + 1.
2. Custom Handling Using Tokens
Consider using a combination of tokenization and traditional Levenshtein distance:
- Tokenize sentences into words.
- Identify and treat swapped positions differently by aligning tokens.
- Calculate total cost with reduced weight for swaps.
Example:
For the input: "I saw the cat" and "the cat I saw", traditional Levenshtein would consider this as six edits (full substitutions) despite merely rearranging. With swap-aware algorithms:
- Split into tokens:
["I", "saw", "the", "cat"]vs["the", "cat", "I", "saw"]. - Realize the swap of positions for:
["I", "saw"]and["the", "cat"]. - Assign the swap operation a lesser cost (e.g., consider one or two operations instead of four).
Table: Key Comparisons
| Metric | Edits Considered | Strengths | Limitations |
| Levenshtein Distance | Insert, Delete, Substitute | Simplicity, wide applicability | Doesn't handle swaps |
| Damerau-Levenshtein | Above plus Transpose | Handles adjacent swaps | Increased computational overhead |
| Custom Handling with Tokens | Strategy-dependent | Tailored for specific contexts | Complexity in implementation |
Use Cases
- Spell Checking: Useful for suggesting corrections.
- DNA Sequencing: Identifying sequences by minimal edits.
- Natural Language Processing: Enhanced by handling rearranged terms.
- Data Deduplication: Detecting similar or duplicate entries where words may be swapped.
Conclusion
While the standard Levenshtein distance is versatile and valuable, it falters in accurately representing semantic or syntactic swaps in text. Extending the algorithm by employing techniques such as the Damerau-Levenshtein distance or token-based approaches can enhance its robustness, particularly useful in applications where the sequence arrangement holds significant meaning. Such adaptations reveal the depth and breadth of text similarity algorithms necessary to accurately measure real-world data, ultimately making computational text analysis more relevant and effective.
Related reading
- Levenshtein Distance Inferring the edit operations from the matrix
- Levenshtein Matrix using only a diagonal strip
- Lexicographic minimum permutation such that all adjacent letters are distinct
- Lexicographically minimal grid path algorithm
- Library for working with potentially infinite graphs defined by neighbor-list functions
- libsvm Shrinking Heuristics
- Lightweight decompression algorithm for embedded use
- Line clipping to arbitary 2D polygon

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 courseTrack 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.