<p>Given two strings <code>word1</code> and <code>word2</code>, return <em>the minimum number of <strong>steps</strong> required to make</em> <code>word1</code> <em>and</em> <code>word2</code> <em>the same</em>.</p>

<p>In one <strong>step</strong>, you can delete exactly one character in either string.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> word1 = &quot;sea&quot;, word2 = &quot;eat&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong> You need one step to make &quot;sea&quot; to &quot;ea&quot; and another step to make &quot;eat&quot; to &quot;ea&quot;.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> word1 = &quot;leetcode&quot;, word2 = &quot;etco&quot;
<strong>Output:</strong> 4
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= word1.length, word2.length &lt;= 500</code></li>
	<li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li>
</ul>

class Solution:

    def minDistance(self, word1: str, word2: str) -> int:

        @cache
        def MD(i: int, j: int) -> int:
            nonlocal word1, word2
            try:
                A = word1[i]
            except IndexError:
                newJ = len(word2)   # skip entirety of other list
                return newJ - j
                
            try:
                B = word2[j]
            except IndexError:
                newI = len(word1)   # skip entirety of other list
                return newI - i

            if A == B:
                return 0 + MD(i + 1, j + 1)
            
            answers = []

            try:
                newI = word1.index(B, i)
                answers.append(
                    newI - i + MD(newI, j)  # skip to letter B in word 1
                )
            except ValueError:
                newI = len(word1)   # skip entirety of both remaining lists
                newJ = len(word2)
                answers.append(newI - i + newJ - j)

            try:
                newJ = word2.index(A, j)
                answers.append(
                    newJ - j + MD(i, newJ)  # skip to letter A in word 2
                )
            except ValueError:
                newI = len(word1)   # skip entirety of both remaining lists
                newJ = len(word2)
                answers.append(newI - i + newJ - j)

            answers.append(
                2 + MD(i + 1, j + 1)    # skip 1 letter in both
            )
            return min(answers)

        return MD(0, 0)

21063