1. Recurrence
if a[i-1] == b[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = 1 + min(dp[i-1][j], # delete
dp[i][j-1], # insert
dp[i-1][j-1]) # replace
Classical dynamic programming formulation for measuring similarity between strings.
dp[i][j] distance
dp[i][0]=i dp[0][j]=j
match/insert/delete/replace
if a[i-1] == b[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = 1 + min(dp[i-1][j], # delete
dp[i][j-1], # insert
dp[i-1][j-1]) # replace
Only previous row needed → O(min(m,n)) by iterating over shorter string horizontally.