Implement Levenshtein distance with the iterative two matrix rows optimization. Store only current and previous row instead of the full matrix to reduce space complexity to O(min(n,m)).
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The Levenshtein distance (also known as edit distance) is the minimum number of single-character edits (insertions, deletions, or substitutions) needed to transform one string into another.
The classic dynamic programming approach uses an (n+1) x (m+1) matrix where n and m are the lengths of the two strings. However, since each row only depends on the previous row, we can optimize the space complexity from O(n*m) to O(min(n,m)) by only keeping the current and previous rows.
Let me implement this with comprehensive explanation and examples:
python
def levenshtein_distance(s1, s2):
"""
Calculate Levenshtein distance between two strings using two-row optimization.
Time Complexity: O(n*m) where n and m are string lengths
Space Complexity: O(min(n,m)) - only storing two rows
Args:
s1: First string
s2: Second string
Returns:
int: The Levenshtein distance
"""
# Ensure s1 is the longer string to optimize space if needed
if len(s1) < len(s2):
s1, s2 = s2, s1
m, n = len(s1), len(s2)
# Initialize two rows
prev_row = list(range(n + 1)) # [0, 1, 2, ..., n]
curr_row = [0] * (n + 1)
# Fill the matrix iteratively
for i in range(1, m + 1):
curr_row[0] = i # First column is just the row number
for j in range(1, n + 1):
# Cost is 0 if characters match, 1 otherwise
cost = 0 if s1[i-1] == s2[j-1] else 1
# Take the minimum of deletion, insertion, or substitution
curr_row[j] = min(
prev_row[j] + 1, # Deletion
curr_row[j-1] + 1, # Insertion
prev_row[j-1] + cost # Substitution
)
# Swap rows for next iteration
prev_row, curr_row = curr_row, prev_row
# prev_row now contains the last computed row
return prev_row[n]
Working through an example with s1 = "kitten" and s2 = "sitting", I can trace how each cell computes the minimum edit distance by considering what operations would be needed at each step.
Starting with prev_row = [0, 1, 2, 3, 4, 5, 6, 7] for the second string and m = 6 for the first string's length, when processing the first character 'k' from s1, curr_row[0] becomes 1. Then for each character in s2, since 'k' doesn't match any of them, the algorithm fills in values by taking the minimum cost across the three operations at each position.
After completing the first row, curr_row becomes [1, 1, 2, 3, 4, 5, 6, 7], which then becomes the new prev_row for the next iteration. This two-row approach optimizes space by only keeping track of the current and previous rows rather than storing the entire matrix. The algorithm continues this process for each character in s1, swapping rows after each iteration until all characters are processed. m, n = len(s1), len(s2)
code
# Initialize previous row: [0, 1, 2, ..., n]
# This represents the first row of the DP table
prev_row = list(range(n + 1))
# Process each character of s1
for i in range(1, m + 1):
# Initialize current row
# First element is the row index (represents deletion cost from s1)
curr_row = [i] + [0] * n
# Process each character of s2
for j in range(1, n + 1):
# Cost of substitution (0 if characters match, 1 otherwise)
substitution_cost = 0 if s1[i-1] == s2[j-1] else 1
# Calculate the minimum cost among three operations:
# Delete from s1, insert into s1, or substitute a character
curr_row[j] = min(
prev_row[j] + 1, # Deletion
curr_row[j-1] + 1, # Insertion
prev_row[j-1] + substitution_cost # Substitution
)
# Move to next iteration
prev_row = curr_row
return prev_row[n]
def levenshtein_distance_with_trace(s1, s2):
"""
Calculate Levenshtein distance and return the edited string for visualization.
code
Returns both the distance and a trace of operations.
"""
if len(s1) < len(s2):
s1, s2 = s2, s1
m, n = len(s1), len(s2)
# Build the full DP matrix to enable backtracking through the operations
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Set up base cases: first row and column represent costs of insertions and deletions
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
# Fill each cell with the minimum cost transformation
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if s1[i-1] == s2[j-1] else 1
dp[i][j] = min(
dp[i-1][j] + 1, # Deletion
dp[i][j-1] + 1, # Insertion
dp[i-1][j-1] + cost # Substitution
)
# Trace back through the matrix to identify which operations were used
def backtrack():
operations = []
i, j = m, n
while i > 0 or j > 0:
if i == 0:
operations.append(f"Insert '{s2[j-1]}'")
j -= 1
elif j == 0:
operations.append(f"Delete '{s1[i-1]}'")
i -= 1
else:
cost = 0 if s1[i-1] == s2[j-1] else 1
if dp[i-1][j-1] + cost == dp[i][j]:
operations.append(f"Match '{s1[i-1]}'" if cost == 0 else f"Replace '{s1[i-1]}' with '{s2[j-1]}'")
i -= 1
j -= 1
elif dp[i-1][j] + 1 == dp[i][j]:
operations.append(f"Delete '{s1[i-1]}'")
i -= 1
else:
operations.append(f"Insert '{s2[j-1]}'")
j -= 1
return list(reversed(operations))
return dp[m][n], backtrack()
def print_matrix(s1, s2):
"""Visualize the DP matrix for educational purposes."""
m, n = len(s1), len(s2)
code
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if s1[i-1] == s2[j-1] else 1
dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + cost)
print(" ", end="")
for char in s2:
print(f"{char:4}", end="")
print()
print(" ", end="")
for j in range(n + 1):
print(f"{dp[0][j]:4}", end="")
print()
for i in range(1, m + 1):
print(f"{s1[i-1]} ", end="")
for j in range(n + 1):
print(f"{dp[i][j]:4}", end="")
print()
return dp
if name == "main":
print("Test 1: Basic example")
s1, s2 = "kitten", "sitting"
dist = levenshtein_distance(s1, s2)
print(f"Distance between '{s1}' and '{s2}': {dist}")
print(f"Expected: 3\n")
code
print("Test 2: Empty strings")
print(f"Distance between '' and 'abc': {levenshtein_distance('', 'abc')}")
print(f"Expected: 3\n")
print("Test 3: Identical strings")
print(f"Distance between 'abc' and 'abc': {levenshtein_distance('abc', 'abc')}")
print(f"Expected: 0\n")
print("Test 4: Completely different")
print(f"Distance between 'abc' and 'xyz': {levenshtein_distance('abc', 'xyz')}")
print(f"Expected: 3\n")
print("Test 5: With trace")
s1, s2 = "saturday", "sunday"
dist, operations = levenshtein_distance_with_trace(s1, s2)
print(f"Distance between '{s1}' and '{s2}': {dist}")
print(f"Expected: 3")
print("Operations:")
for op in operations:
print(f" - {op}\n")
print("Test 6: Matrix visualization")
print(f"Matrix for '{s1}' and '{s2}':")
print_matrix(s1, s2)
print()
print("Test 7: Performance on longer strings")
import time
s1 = "algorithm" * 10
s2 = "altruistic" * 10
start = time.time()
dist = levenshtein_distance(s1, s2)
end = time.time()
print(f"Distance: {dist}")
print(f"Time taken: {(end - start) * 1000:.3f} ms")
class LevenshteinDistance:
"""
Levenshtein Distance calculator with two-row optimization.
code
This implementation uses O(min(n,m)) space complexity by maintaining
only the current and previous rows of the DP table.
"""
@staticmethod
def compute(s1, s2):
"""
Compute Levenshtein distance with optimized space complexity.
Args:
s1: First string
s2: Second string
Returns:
int: The minimum edit distance
Time Complexity: O(n*m)
Space Complexity: O(min(n,m))
"""
if len(s1) < len(s2):
s1, s2 = s2, s1
m, n = len(s1), len(s2)
prev_row = list(range(n + 1))
for i in range(1, m + 1):
curr_row = [i] + [0] * n
for j in range(1, n + 1):
if s1[i-1] == s2[j-1]:
curr_row[j] = prev_row[j-1]
else:
curr_row[j] = 1 + min(prev_row[j], curr_row[j-1], prev_row[j-1])
prev_row = curr_row
return prev_row[n]
@staticmethod
def compute_with_details(s1, s2, verbose=False):
"""
Compute distance with optional visualization of the process.
"""
if len(s1) < len(s2):
s1, s2 = s2, s1
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
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], dp[i][j-1], dp[i-1][j-1])
if verbose:
LevenshteinDistance._print_matrix(s1, s2, dp)
return dp[m][n]
@staticmethod
def _print_matrix(s1, s2, dp):
"""Print the DP matrix for visualization."""
m, n = len(s1), len(s2)
print(" ", end="")
for char in s2:
print(f"{char:4}", end="")
print()
print(" ", end="")
for j in range(n + 1):
print(f"{dp[0][j]:4}", end="")
print()
for i in range(1, m + 1):
print(f"{s1[i-1]:4}", end="")
for j in range(n + 1):
print(f"{dp[i][j]:4}", end="")
print()