"""Edit (Levenshtein) distance.

Idea
----
The minimum number of single-character insertions, deletions and
substitutions that turn ``a`` into ``b``. ``dp[i][j]`` is the distance
between ``a[:i]`` and ``b[:j]``:

* if ``a[i-1] == b[j-1]`` the last characters are free: ``dp[i-1][j-1]``
* otherwise 1 + min(delete ``dp[i-1][j]``, insert ``dp[i][j-1]``,
  substitute ``dp[i-1][j-1]``)

Only the previous row is needed, so we keep two rows.

Complexity
----------
Time:  O(m * n)
Space: O(n)
"""


def edit_distance(a: str, b: str) -> int:
    """Return the Levenshtein distance between ``a`` and ``b``."""
    prev = list(range(len(b) + 1))
    for i, ca in enumerate(a, start=1):
        cur = [i] + [0] * len(b)
        for j, cb in enumerate(b, start=1):
            if ca == cb:
                cur[j] = prev[j - 1]
            else:
                cur[j] = 1 + min(prev[j], cur[j - 1], prev[j - 1])
        prev = cur
    return prev[-1]
