Edit Distance (the distance between strings)
Edit Distance (also known as the Levenshtein distance) is a classic dynamic programming problem that measures the smallest number of operations needed to turn one string into another.
The allowed operations are:
- inserting a character,
- deleting a character,
- replacing one character with another.
Each operation costs 1.
Problem definition
Two strings are given:
s– the source string,t– the target string.
Find the smallest number of operations that turn the string s into the string t.
Example:
s = "kitten"t = "sitting"
The result is 3:
kitten → sitten (replace k with s)
sitten → sittin (replace e with i)
sittin → sitting (insert g at the end)
Why dynamic programming?
If we look at the prefixes of the strings (their initial parts), the problem naturally
breaks down into smaller subproblems: to turn "kitten" into "sitting",
it is enough to know the solutions for shorter prefixes, for example "kitte" → "sittin".
Edit Distance has both properties needed for dynamic programming:
- optimal substructure – the optimal solution consists of optimal solutions for shorter prefixes,
- overlapping subproblems – the same pair of prefixes appears in many different branches of the recursion.
DP state
We define:
dp[i][j] = the smallest number of operations
that turn the first i characters of s
into the first j characters of t
The final answer is dp[n][m], where n and m are the lengths of the strings.
Base cases
dp[0][j] = j– from the empty string we get tojcharacters withjinsertions,dp[i][0] = i– fromicharacters we get to the empty string withideletions.
Transition (DP relation)
We look at the last characters of the prefixes, s[i-1] and t[j-1]. If they are equal, we need no new operation:
dp[i][j] = dp[i-1][j-1]
If they are different, we choose the cheapest of the three operations:
dp[i][j] = 1 + min(
dp[i-1][j], // delete the character s[i-1]
dp[i][j-1], // insert the character t[j-1]
dp[i-1][j-1] // replace s[i-1] with t[j-1]
)
- Up (
dp[i-1][j]): a character fromswas deleted, andtdid not move. - Left (
dp[i][j-1]): we inserted a character fromt, andsdid not move. - Diagonal (
dp[i-1][j-1]): both characters are processed, by a replacement or with no change.
DP table for the example kitten → sitting
The rows correspond to the prefixes of the string s = "kitten", and the columns to the prefixes of the string
t = "sitting". The symbol ε stands for the empty string. The table is filled
row by row, from left to right, because each cell depends only on the cells above, to the left and up-left.
| ε | s | i | t | t | i | n | g | |
|---|---|---|---|---|---|---|---|---|
| ε | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| k | 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| i | 2 | 2 | 1 | 2 | 3 | 4 | 5 | 6 |
| t | 3 | 3 | 2 | 1 | 2 | 3 | 4 | 5 |
| t | 4 | 4 | 3 | 2 | 1 | 2 | 3 | 4 |
| e | 5 | 5 | 4 | 3 | 2 | 2 | 3 | 4 |
| n | 6 | 6 | 5 | 4 | 3 | 3 | 2 | 3 |
The answer is in the bottom right corner: dp[6][7] = 3. For example, the cell dp[1][1]
(k → s) is 1, because the characters are different and the smallest of the three neighboring values is 0.
Implementation (C++)
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // for the min function
using namespace std;
// The smallest of three numbers
int min3(int a, int b, int c) {
return min(a, min(b, c));
}
int main() {
string s, t;
cin >> s >> t;
int n = s.size();
int m = t.size();
// dp[i][j] - the smallest number of operations to turn the first i characters
// stringa s pretvori u prvih j znakova stringa t.
// vector instead of the array dp[n + 1][m + 1], because a variable-length
// array is not standard C++ and does not fit on the stack for long strings.
vector<vector<int>> dp(n + 1, vector<int>(m + 1));
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (i == 0)
dp[i][j] = j; // ubacujemo j znakova
else if (j == 0)
dp[i][j] = i; // we delete i characters
else if (s[i - 1] == t[j - 1])
dp[i][j] = dp[i - 1][j - 1]; // the last characters are the same
else
dp[i][j] = 1 + min3(
dp[i - 1][j], // delete the character s[i-1]
dp[i][j - 1], // ubacivanje znaka t[j-1]
dp[i - 1][j - 1] // replace s[i-1] with t[j-1]
);
}
}
cout << "Edit distance: " << dp[n][m] << endl;
return 0;
}
int dp[n + 1][m + 1]?
An array whose length is given by a variable is not part of standard C++, and it is created on the stack, which is small
(usually 8 MB). For two strings of length 3000 the table takes about 36 MB and the program crashes
(segmentation fault). A vector is created in dynamic memory and does not have this problem.
Also, the min function needs the header <algorithm>.
Memory optimization: two rows instead of the whole table
Computing row i needs only row i − 1. So it is enough to keep
two rows, and the memory drops from O(n · m) to O(m).
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string s, t;
cin >> s >> t;
int n = s.size();
int m = t.size();
// Row i needs only row i - 1, so we keep two rows.
vector<int> prethodni(m + 1), tekuci(m + 1);
// Row i = 0: from the empty string to the first j characters of t
for (int j = 0; j <= m; j++)
prethodni[j] = j;
for (int i = 1; i <= n; i++) {
tekuci[0] = i; // j = 0: we delete all i characters
for (int j = 1; j <= m; j++) {
if (s[i - 1] == t[j - 1])
tekuci[j] = prethodni[j - 1];
else
tekuci[j] = 1 + min({prethodni[j], // brisanje
tekuci[j - 1], // ubacivanje
prethodni[j - 1]}); // zamena
}
swap(prethodni, tekuci); // the current row becomes the previous one
}
// After the last swap the result is in the array prethodni
cout << "Edit distance: " << prethodni[m] << endl;
return 0;
}
This variant gives only the number of operations. If you also need to print which operations
were performed, the whole table is needed, because the path is reconstructed backwards from dp[n][m].
That is exactly what the interactive example below does.
Time and space complexity
- Time complexity: O(n · m)
- Space complexity: O(n · m) with the whole table, or O(m) with two rows
where n and m are the lengths of the strings.
Interactive example: the DP table and the sequence of operations
Enter two short strings (at most 12 characters) and press the button. The filled DP table will be shown, with the path that leads to the solution marked and the order of the operations.
Practical applications
Edit Distance is used in:
- spell checking and suggesting corrections (“Did you mean...?”),
- search that tolerates typing mistakes,
- bioinformatics, for comparing DNA sequences,
- natural language processing and comparing the similarity of texts.
Connection with other DP problems
-
Longest Common Subsequence (LCS) – the same table structure over two strings;
if only deletions and insertions are allowed, the distance is
n + m − 2·LCS. - Grid DP – each cell depends on the neighbors above, to the left and diagonally.
- String alignment problems (sequence alignment).
Understanding this problem is a big step towards mastering advanced dynamic programming.
| Previous |<DP: grid dynamic programming |
Next Algorithm complexity: replacing iteration with a formula (SR)>| |
Edit Distance (Levenshtein Distance)
Edit Distance is a classic dynamic programming problem that measures the minimum number of operations required to transform one string into another.
The allowed operations are:
- Inserting a character
- Deleting a character
- Replacing a character
Each operation has a cost of 1.
Problem Definition
Given two strings:
s– the source stringt– the target string
Determine the minimum number of operations required
to transform string s into string t.
Example:
s = "kitten"t = "sitting"
Result: 3 (replacement, replacement, insertion)
For example, `"kitten"` can be transformed into `"sitting"` in three operations: 1. Replace `k` with `s`: `"sitten"`. 2. Replace `e` with `i`: `"sittin"`. 3. Insert `g` at the end: `"sitting"`. Therefore, the edit distance is 3.
Note: Standard Levenshtein distance does not treat swapping two adjacent characters as a single operation. If adjacent transpositions are allowed as one operation, a related variant is the Damerau–Levenshtein distance.
Why Dynamic Programming?
When we consider prefixes of the strings, the problem naturally breaks down into smaller subproblems.
Edit Distance has:
- Optimal substructure
- Overlapping subproblems
This makes it an ideal problem for dynamic programming.
DP State
We define:
dp[i][j] = the minimum number of operations
required to transform the first i characters of string s
into the first j characters of string t
Base Cases
dp[0][j] = j(insert j characters)dp[i][0] = i(delete i characters)
Transition (DP Recurrence)
If the last characters are equal:
dp[i][j] = dp[i-1][j-1]
If they are different:
dp[i][j] = 1 + min(
dp[i-1][j], // deletion
dp[i][j-1], // insertion
dp[i-1][j-1] // replacement
)
Implementation (C++)
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int min3(int a, int b, int c) {
return min(a, min(b, c));
}
int main() {
string source, target;
cin >> source >> target;
int n = source.size();
int m = target.size();
vector<vector<int>> dp(
n + 1, vector<int>(m + 1, 0)
);
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
if (i == 0) {
dp[i][j] = j;
} else if (j == 0) {
dp[i][j] = i;
} else if (source[i - 1] == target[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + min3(
dp[i - 1][j], // deletion
dp[i][j - 1], // insertion
dp[i - 1][j - 1] // replacement
);
}
}
}
cout << "Edit distance: " << dp[n][m];
return 0;
}
Example Input and Output
Input:
kitten sitting
Output:
Edit distance: 3
The minimum edit distance is 3. We can transform kitten
into sitting by performing two replacements and one insertion.
Time and Space Complexity
- Time complexity: O(n · m)
- Space complexity: O(n · m)
where n and m are the lengths of the strings.
Advanced Note: Space Optimization
The standard implementation stores the entire DP table and therefore requires O(n · m) space. However, each cell depends only on the previous row and the current row. This means we can reduce the space complexity to O(min(n, m)) by maintaining only two rows.
The time complexity remains O(n · m), but the memory usage can be significantly reduced for long strings. This optimization is useful when the edit distance is needed but the complete DP table is not required.
Space-Optimized Implementation (Two DP Arrays)
The standard Edit Distance algorithm stores the entire DP table, which requires O(n · m) space. However, each state depends only on the previous row and the already computed values in the current row. Therefore, we can optimize the memory usage by maintaining only two one-dimensional DP arrays.
The previous array stores the results from the previous
row, while the current array stores the results for
the row currently being calculated. After each row is completed,
the two arrays are swapped.
To achieve O(min(n, m)) space complexity, we make
the shorter string the second string, so that the DP arrays have
only m + 1 elements, where m is the length
of the shorter string.
Implementation (C++)
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int min3(int a, int b, int c) {
return min(a, min(b, c));
}
int main() {
string source, target;
cin >> source >> target;
// Keep target as the shorter string
if (target.size() > source.size()) {
swap(source, target);
}
int n = static_cast<int>(source.size());
int m = static_cast<int>(target.size());
vector<int> previous(m + 1);
vector<int> current(m + 1);
// Base case: converting an empty string into a prefix of target
for (int j = 0; j <= m; j++) {
previous[j] = j;
}
for (int i = 1; i <= n; i++) {
// Convert a prefix of source into an empty string
current[0] = i;
for (int j = 1; j <= m; j++) {
if (source[i - 1] == target[j - 1]) {
current[j] = previous[j - 1];
} else {
current[j] = 1 + min3(
previous[j], // deletion
current[j - 1], // insertion
previous[j - 1] // replacement
);
}
}
// The current row becomes the previous row
swap(previous, current);
}
cout << "Edit distance: " << previous[m] << '\n';
return 0;
}
Example Input and Output
Input:
kitten sitting
Output:
Edit distance: 3
Complexity Analysis
- Time Complexity: O(n · m), because each DP state is calculated once.
- Space Complexity: O(min(n, m)), because only two arrays of length min(n, m) + 1 are stored.
This optimization is useful when working with long strings and when only the final edit distance is required. If the complete DP table is needed to reconstruct the actual sequence of edits, the standard two-dimensional implementation is more convenient.
Practical Applications
Edit Distance is used in:
- Spell checking
- Approximate string matching and fuzzy search
- Bioinformatics (DNA sequences)
- Natural language processing
Connections to Other DP Problems
Edit Distance is related to:
- Longest Common Subsequence (LCS)
- Grid DP problems
- String alignment problems
Understanding this problem is an important step toward mastering more advanced dynamic programming techniques.
