Edit Distance in Python

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m = len(word1)
        n = len(word2)

        # Create a 2D array to store the minimum number of operations
        dp = [[0] * (n + 1) for _ in range(m + 1)]

        # Fill the first row and column of the dp array
        for i in range(1, m + 1):
            dp[i][0] = i
        for j in range(1, n + 1):
            dp[0][j] = j

        # Fill the dp array
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if word1[i - 1] == word2[j - 1]:
                    # If the characters are the same, no operation is needed
                    dp[i][j] = dp[i - 1][j - 1]
                else:
                    # If the characters are different, choose the minimum of insert, delete, or replace
                    dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1])

        # Return the minimum number of operations
        return dp[m][n]

Next