Edit Distance

interview_workbook/leetcode/dp_2d /app/src/interview_workbook/leetcode/dp_2d/edit_distance.py
View Source

Algorithm Notes

Summary: Edit Distance — notes not yet curated.
Time: Estimate via loops/recurrences; common classes: O(1), O(log n), O(n), O(n log n), O(n^2)
Space: Count auxiliary structures and recursion depth.
Tip: See the Big-O Guide for how to derive bounds and compare trade-offs.

Big-O Guide

Source

"""
Edit Distance

TODO: Add problem description
"""

from src.interview_workbook.leetcode._registry import register_problem
from src.interview_workbook.leetcode._types import Category, Difficulty


class Solution:
    def solve(self, *args) -> int:
        """Compute minimum edit distance (Levenshtein distance)."""
        if len(args) != 2:
            return ""
        word1, word2 = args
        m, n = len(word1), len(word2)
        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 word1[i - 1] == word2[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
                    )
        return dp[m][n]


def demo():
    """Run a demo for the Edit Distance problem."""
    solver = Solution()
    word1 = "horse"
    word2 = "ros"
    result = solver.solve(word1, word2)
    return str(result)


register_problem(
    id=72,
    slug="edit_distance",
    title="Edit Distance",
    category=Category.DP_2D,
    difficulty=Difficulty.HARD,
    tags=["string", "dynamic_programming"],
    url="https://leetcode.com/problems/edit-distance/",
    notes="",
)