Skip to content

Commit db6ef56

Browse files
authored
Merge pull request #1150 from kosuri-indu/add/edit-distance
Added: DP algorithm - Edit Distance
2 parents 0c57ef7 + eb6effd commit db6ef56

File tree

1 file changed

+212
-0
lines changed

1 file changed

+212
-0
lines changed
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
---
2+
id: edit-distance
3+
title: Edit Distance using Dynamic Programming
4+
sidebar_label: Edit Distance
5+
tags: [python, java, c++, javascript, programming, algorithms, dynamic programming, tutorial, in-depth]
6+
description: In this tutorial, we will learn about the Edit Distance problem and its solution using Dynamic Programming in Python, Java, C++, and JavaScript with detailed explanations and examples.
7+
---
8+
9+
# Edit Distance using Dynamic Programming
10+
11+
Edit Distance, also known as Levenshtein distance, is a classic problem in computer science that measures the minimum number of operations required to transform one string into another. The allowed operations are insertion, deletion, and substitution.
12+
13+
## Problem Statement
14+
15+
Given two strings, find the minimum number of operations required to transform one string into the other.
16+
17+
### Intuition
18+
19+
The problem can be solved efficiently using dynamic programming by breaking it down into subproblems. The idea is to create a DP table where `dp[i][j]` represents the edit distance between the first `i` characters of the first string and the first `j` characters of the second string.
20+
21+
## Dynamic Programming Approach
22+
23+
Using dynamic programming, we fill the table based on the recurrence relation:
24+
- If the characters are the same, no new operation is needed.
25+
- If the characters are different, consider the minimum cost of the three operations: insertion, deletion, and substitution.
26+
27+
## Pseudocode for Edit Distance using DP
28+
29+
#### Initialize:
30+
31+
```markdown
32+
for i from 0 to m:
33+
dp[i][0] = i
34+
for j from 0 to n:
35+
dp[0][j] = j
36+
37+
for i from 1 to m:
38+
for j from 1 to n:
39+
if str1[i-1] == str2[j-1]:
40+
dp[i][j] = dp[i-1][j-1]
41+
else:
42+
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
43+
44+
return dp[m][n]
45+
```
46+
47+
### Example Output:
48+
49+
Given the strings:
50+
- str1 = "kitten"
51+
- str2 = "sitting"
52+
53+
The minimum edit distance between `str1` and `str2` is `3`.
54+
55+
### Output Explanation:
56+
57+
The edit distance of `3` can be achieved by the following operations:
58+
59+
- Replace 'k' with 's': kitten -> sitten
60+
- Replace 'e' with 'i': sitten -> sittin
61+
- Insert 'g' at the end: sittin -> sitting
62+
63+
Therefore, the output is: `Minimum edit distance is: 3`
64+
65+
## Implementing Edit Distance using DP
66+
67+
### Python Implementation
68+
69+
```python
70+
def edit_distance(str1, str2):
71+
m, n = len(str1), len(str2)
72+
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)] # DP table initialization
73+
74+
for i in range(m + 1):
75+
for j in range(n + 1):
76+
if i == 0:
77+
dp[i][j] = j # If first string is empty, insert all characters of second string
78+
elif j == 0:
79+
dp[i][j] = i # If second string is empty, remove all characters of first string
80+
elif str1[i - 1] == str2[j - 1]:
81+
dp[i][j] = dp[i - 1][j - 1]
82+
else:
83+
dp[i][j] = 1 + min(dp[i - 1][j], # Remove
84+
dp[i][j - 1], # Insert
85+
dp[i - 1][j - 1]) # Replace
86+
87+
return dp[m][n]
88+
89+
str1 = "kitten"
90+
str2 = "sitting"
91+
print("Minimum edit distance is:", edit_distance(str1, str2))
92+
93+
```
94+
95+
### Java Implementation
96+
97+
```java
98+
public class EditDistance {
99+
public static int editDistance(String str1, String str2) {
100+
int m = str1.length();
101+
int n = str2.length();
102+
int[][] dp = new int[m + 1][n + 1]; // DP table initialization
103+
104+
for (int i = 0; i <= m; i++) {
105+
for (int j = 0; j <= n; j++) {
106+
if (i == 0) {
107+
dp[i][j] = j; // If first string is empty, insert all characters of second string
108+
} else if (j == 0) {
109+
dp[i][j] = i; // If second string is empty, remove all characters of first string
110+
} else if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
111+
dp[i][j] = dp[i - 1][j - 1];
112+
} else {
113+
dp[i][j] = 1 + Math.min(dp[i - 1][j], // Remove
114+
Math.min(dp[i][j - 1], // Insert
115+
dp[i - 1][j - 1])); // Replace
116+
}
117+
}
118+
}
119+
120+
return dp[m][n];
121+
}
122+
123+
public static void main(String[] args) {
124+
String str1 = "kitten";
125+
String str2 = "sitting";
126+
System.out.println("Minimum edit distance is: " + editDistance(str1, str2));
127+
}
128+
}
129+
130+
```
131+
### C++ Implementation
132+
133+
```cpp
134+
#include <iostream>
135+
#include <vector>
136+
#include <algorithm>
137+
using namespace std;
138+
139+
int editDistance(string str1, string str2) {
140+
int m = str1.length();
141+
int n = str2.length();
142+
vector<vector<int>> dp(m + 1, vector<int>(n + 1)); // DP table initialization
143+
144+
for (int i = 0; i <= m; i++) {
145+
for (int j = 0; j <= n; j++) {
146+
if (i == 0) {
147+
dp[i][j] = j; // If first string is empty, insert all characters of second string
148+
} else if (j == 0) {
149+
dp[i][j] = i; // If second string is empty, remove all characters of first string
150+
} else if (str1[i - 1] == str2[j - 1]) {
151+
dp[i][j] = dp[i - 1][j - 1];
152+
} else {
153+
dp[i][j] = 1 + min({dp[i - 1][j], // Remove
154+
dp[i][j - 1], // Insert
155+
dp[i - 1][j - 1]}); // Replace
156+
}
157+
}
158+
}
159+
160+
return dp[m][n];
161+
}
162+
163+
int main() {
164+
string str1 = "kitten";
165+
string str2 = "sitting";
166+
cout << "Minimum edit distance is: " << editDistance(str1, str2) << endl;
167+
return 0;
168+
}
169+
170+
```
171+
172+
### JavaScript Implementation
173+
174+
```javascript
175+
function editDistance(str1, str2) {
176+
let m = str1.length;
177+
let n = str2.length;
178+
let dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); // DP table initialization
179+
180+
for (let i = 0; i <= m; i++) {
181+
for (let j = 0; j <= n; j++) {
182+
if (i === 0) {
183+
dp[i][j] = j; // If first string is empty, insert all characters of second string
184+
} else if (j === 0) {
185+
dp[i][j] = i; // If second string is empty, remove all characters of first string
186+
} else if (str1[i - 1] === str2[j - 1]) {
187+
dp[i][j] = dp[i - 1][j - 1];
188+
} else {
189+
dp[i][j] = 1 + Math.min(dp[i - 1][j], // Remove
190+
dp[i][j - 1], // Insert
191+
dp[i - 1][j - 1]); // Replace
192+
}
193+
}
194+
}
195+
196+
return dp[m][n];
197+
}
198+
199+
let str1 = "kitten";
200+
let str2 = "sitting";
201+
console.log("Minimum edit distance is:", editDistance(str1, str2));
202+
203+
```
204+
205+
## Complexity Analysis
206+
207+
- Time Complexity: $O(m \times n)$, where m and n are the lengths of the two strings.
208+
- Space Complexity: $O(m \times n)$, for storing the DP table.
209+
210+
## Conclusion
211+
212+
Dynamic programming provides an efficient solution for the Edit Distance problem by breaking it into subproblems and storing intermediate results. This technique can be extended to solve other problems with overlapping subproblems and optimal substructure properties.

0 commit comments

Comments
 (0)