<p>Given two strings <code>text1</code> and <code>text2</code>, return <em>the length of their longest <strong>common subsequence</strong>. </em>If there is no <strong>common subsequence</strong>, return <code>0</code>.</p>

<p>A <strong>subsequence</strong> of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.</p>

<ul>
	<li>For example, <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;abcde&quot;</code>.</li>
</ul>

<p>A <strong>common subsequence</strong> of two strings is a subsequence that is common to both strings.</p>

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

<pre>
<strong>Input:</strong> text1 = &quot;abcde&quot;, text2 = &quot;ace&quot; 
<strong>Output:</strong> 3  
<strong>Explanation:</strong> The longest common subsequence is &quot;ace&quot; and its length is 3.
</pre>

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

<pre>
<strong>Input:</strong> text1 = &quot;abc&quot;, text2 = &quot;abc&quot;
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest common subsequence is &quot;abc&quot; and its length is 3.
</pre>

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

<pre>
<strong>Input:</strong> text1 = &quot;abc&quot;, text2 = &quot;def&quot;
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is no such common subsequence, so the result is 0.
</pre>

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

<ul>
	<li><code>1 &lt;= text1.length, text2.length &lt;= 1000</code></li>
	<li><code>text1</code> and <code>text2</code> consist of only lowercase English characters.</li>
</ul>

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        from collections import defaultdict
        letters = defaultdict(list)
        for ind, c in enumerate(text2):
            letters[c].append(ind)
            
        def find_next(intlist, lowerbound):            
            if len(intlist) == 0 or intlist[-1] < lowerbound:
                return None
            i = 0
            while intlist[i] < lowerbound:
                i += 1
            return intlist[i]
            
        
        memo = {}
        l1, l2 = len(text1), len(text2)
        def dp(ind1, ind2):
            
            if ind1 == l1 or ind2 == l2:
                return 0
            if (ind1, ind2) not in memo:                
                c = text1[ind1]
                next_ind = find_next(letters[c], ind2)
                # print(f'dp called {ind1}, {ind2}, char={c}, next={next_ind}')
                if next_ind is None:
                    memo[(ind1, ind2)] = dp(ind1 + 1, ind2)
                else:
                    memo[(ind1, ind2)] = max(dp(ind1 + 1, ind2), 1 + dp(ind1 + 1, next_ind + 1))
                    
            return memo[(ind1, ind2)]
        
        ans = dp(0, 0)
        # print(memo)
        return ans
            
249721