1. Understand the Goal: The user wants a program that implements the edit distance (Levenshtein distance) algorithm.
-
Identify the Core Concept:
- Levenshtein Distance: It's a metric for measuring the difference between two sequences. It's defined as the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one word into the other.
- Inputs: Two strings (e.g., "kitten", "sitting").
- Output: An integer representing the distance.
-
Choose a Programming Language: Python is a great choice for this because it's readable, widely used in algorithm contexts, and handles strings easily. C++ or Java are also good, but Python is usually the default for "write a program" unless specified otherwise. I will provide the solution in Python, maybe add C++ or JavaScript if I feel extra thorough, but Python is the priority.
-
Determine the Algorithm:
- Naive Recursive: Exponential time complexity O(3n). Too slow for practical use but good for understanding.
- Dynamic Programming (DP): This is the standard approach. Time complexity O(m×n), where m and n are string lengths. Space complexity O(m×n) for the full matrix, or O(min(m,n)) for the optimized space version.
-
Drafting the Dynamic Programming Solution (Matrix Approach):
- Let s1 be string 1 (length m) and s2 be string 2 (length n).
- Create a matrix dp of size .
-
Refining the Implementation (Python):
def levenshtein_distance(s1, s2):
m, n = len(s1), len(s2)
# Create a matrix to store results
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Initialize base cases
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
# Fill the matrix
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j], # Deletion
dp[i][j - 1], # Insertion
dp[i - 1][j - 1]) # Substitution
return dp[m][n]
-
Adding Context/Explanation:
- Just the code is okay, but a good response explains how it works.
- Mention the operations: Insert, Delete, Substitute.
- Explain the DP table concept.
- Provide test cases to show it working.
-
Alternative Approach (Optimized Space):
- The matrix takes O(m×n) space. We only need the previous row to calculate the current row.
- This reduces space to O(min(m,n)).
- Decision: For a general request, the standard DP matrix is easier to understand and debug. I will provide the standard matrix solution as the primary answer but mention the optimization.
-
Review and Finalize:
- Check for off-by-one errors (common in DP string problems). The indices in the string are 0-based, but the DP table is 1-based (conceptually).
- s1[i−1] corresponds to the i-th character in the DP table row. Correct.
- Formatting: Use markdown code blocks.
-
Constructing the Output:
- Introduction: Define the algorithm briefly.
- Code (Python): The clean, commented implementation.
- Example Usage: Run it with "kitten" and "sitting" (expected 3).
- Explanation: Break down the logic (Base cases, Rules).
- (Optional but nice) Recursive version vs Iterative version note.
Let's stick to Python for clarity.
Self-Correction during drafting: Should I use a library like numpy? No, standard library is better for a fundamental algorithm request. It shouldn't have external dependencies.
Code check:
s1 = "kitten", s2 = "sitting"
k -> s (sub)
i -> i
t -> t
t -> t
e -> i (sub)
n -> n
"" -> g (ins)
Total: 3.
The logic holds.
Let's write the response.
Here is a complete implementation of the Levenshtein Distance algorithm in Python.
This implementation uses Dynamic Programming. It builds a matrix where each cell represents the cost (number of edits) required to transform a prefix of the first string into a prefix of the second string.
Python Implementation
def levenshtein_distance(s1, s2):
"""
Calculates the Levenshtein distance between two strings
using a dynamic programming approach.
Args:
s1 (str): The first string.
s2 (str): The second string.
Returns:
int: The minimum number of single-character edits
(insertions, deletions, or substitutions)
required to change s1 into s2.
"""
# Get lengths of both strings
len1 = len(s1)
len2 = len(s2)
# Create a matrix (table) of size (len1 + 1) x (len2 + 1)
# initialized with zeros.
dp = [[0] * (len2 + 1) for _ in range(len1 + 1)]
# Initialize the first row and column.
# If one string is empty, the distance is the length of the other
# (requiring that many insertions/deletions).
for i in range(len1 + 1):
dp[i][0] = i
for j in range(len2 + 1):
dp[0][j] = j
# Fill the matrix based on the cost of operations
for i in range(1, len1 + 1):
for j in range(1, len2 + 1):
# If characters are the same, cost is 0 (no edit needed)
if s1[i - 1] == s2[j - 1]:
cost = 0
else:
cost = 1
# Take the minimum of three possible operations:
# 1. Deletion: dp[i-1][j] + 1
# 2. Insertion: dp[i][j-1] + 1
# 3. Substitution: dp[i-1][j-1] + cost
dp[i][j] = min(
dp[i - 1][j] + 1, # Deletion
dp[i][j - 1] + 1, # Insertion
dp[i - 1][j - 1] + cost # Substitution
)
# The bottom-right cell contains the Levenshtein distance
return dp[len1][len2]
# --- Example Usage ---
if __name__ == "__main__":
string_a = "kitten"
string_b = "sitting"
distance = levenshtein_distance(string_a, string_b)
print(f"String A: {string_a}")
print(f"String B: {string_b}")
print(f"Levenshtein Distance: {distance}")
# Another example
print(f"Distance between 'book' and 'back': {levenshtein_distance('book', 'back')}")
How it Works
- The Matrix: We create a grid (matrix) where the rows represent characters of string
s1 and columns represent characters of string s2.
- Initialization:
- The first row represents transforming an empty string into
s2 (insertions).
- The first column represents transforming
s1 into an empty string (deletions).
- The Logic: We iterate through every cell. At any point
dp[i][j], we look at the previous neighbors:
- Match: If the current characters match, we carry over the value from the diagonal (top-left) without adding a cost.
- Mismatch: We take the minimum value of the three neighbors (Left, Top, Diagonal) and add 1.
- Result: The value in the bottom-right corner of the matrix is the minimum edit distance.
Example Output
String A: kitten
String B: sitting
Levenshtein Distance: 3
Distance between 'book' and 'back': 2
Complexity
- Time Complexity: O(m×n), where m and n are the lengths of the two strings. We must fill every cell in the matrix.
- Space Complexity: O(m× to store the matrix. (Note: This can be optimized to by only storing the current and previous rows, but the matrix version is much easier to understand).