Implemented a Python function computing Levenshtein distance using the Wagner-Fischer algorithm optimized to O(min(N,M)) space by storing only two rows and swapping inputs to minimize memory.
One simple way to score how “close” two strings are is the Levenshtein edit distance: the minimum number of insertions, deletions or substitutions required to turn one string into the other. The Wagner–Fischer dynamic programme fills a ((|s|{+}1)\times(|t|{+}1)) table of these scores, but if you look at the recurrence
D[i,j] = min(
D[i−1,j] + 1, # delete s[i−1]
D[i,j−1] + 1, # insert t[j−1]
D[i−1,j−1] + [s[i−1]!=t[j−1]]# substitute
)
def levenshtein_distance(s: str, t: str) -> int:
"""
Compute the Levenshtein edit distance between two strings using the
Wagner–Fischer algorithm with O(min(len(s), len(t))) space.
:param s: first string
:param t: second string
:return: minimum number of edits (insertions, deletions, substitutions)
to turn s into t
"""
# Ensure t is the shorter string to keep the row array small
if len(s) < len(t):
s, t = t, s
# previous_row[j] holds D[i−1, j], current_row[j] holds D[i, j]
previous_row = list(range(len(t) + 1))
for i, c1 in enumerate(s, start=1):
current_row = [i] + [0] * len(t)
for j, c2 in enumerate(t, start=1):
insert_cost = current_row[j - 1] + 1
delete_cost = previous_row[j] + 1
subst_cost = previous_row[j - 1] + (c1 != c2)
current_row[j] = min(insert_cost, delete_cost, subst_cost)
# Slide the window: current_row becomes previous_row on next iteration
previous_row = current_row
return previous_row[-1]
# Example usage
if __name__ == "__main__":
print(levenshtein_distance("kitten", "sitting")) # outputs 3
print(levenshtein_distance("flaw", "lawn")) # outputs 2
This runs in (O(|s|\cdot|t|)) time like the full Wagner–Fischer algorithm, but only allocates two lists of length (\min(|s|,|t|)+1), so its auxiliary space is (O(\min(|s|,|t|))).