<p>Given two strings <code>str1</code> and <code>str2</code>, return <em>the shortest string that has both </em><code>str1</code><em> and </em><code>str2</code><em> as <strong>subsequences</strong></em>. If there are multiple valid strings, return <strong>any</strong> of them.</p>

<p>A string <code>s</code> is a <strong>subsequence</strong> of string <code>t</code> if deleting some number of characters from <code>t</code> (possibly <code>0</code>) results in the string <code>s</code>.</p>

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

<pre>
<strong>Input:</strong> str1 = &quot;abac&quot;, str2 = &quot;cab&quot;
<strong>Output:</strong> &quot;cabac&quot;
<strong>Explanation:</strong> 
str1 = &quot;abac&quot; is a subsequence of &quot;cabac&quot; because we can delete the first &quot;c&quot;.
str2 = &quot;cab&quot; is a subsequence of &quot;cabac&quot; because we can delete the last &quot;ac&quot;.
The answer provided is the shortest such string that satisfies these properties.
</pre>

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

<pre>
<strong>Input:</strong> str1 = &quot;aaaaaaaa&quot;, str2 = &quot;aaaaaaaa&quot;
<strong>Output:</strong> &quot;aaaaaaaa&quot;
</pre>

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

<ul>
	<li><code>1 &lt;= str1.length, str2.length &lt;= 1000</code></li>
	<li><code>str1</code> and <code>str2</code> consist of lowercase English letters.</li>
</ul>

class Solution:
    def shortestCommonSupersequence(self, text1: str, text2: str) -> str:
        dp = {}
        def recur(i,j):
            if i>=len(text1) or j>=len(text2):
                return ""
            
            if (i,j) in dp:
                return dp[(i,j)]

            if text1[i]==text2[j]:
                dp[(i,j)] = text1[i]+recur(i+1,j+1)
            else:
                x = recur(i+1,j)
                y = recur(i,j+1)
                if len(x)>len(y):
                    dp[(i,j)] = x
                else:
                    dp[(i,j)] = y

            return dp[(i,j)]
        
        lcs = recur(0,0)
        print(lcs)
        it1 = 0
        it2 = 0
        lcsPos = 0
        final_ans = ""
        while lcsPos<len(lcs):
            #find lcsPos in string1
            while lcs[lcsPos]!=text1[it1]:
                final_ans+=text1[it1]
                it1+=1
            #it1 will never go out of bound since lcs is created from it

            #find lcsPos in string2
            while lcs[lcsPos]!=text2[it2]:
                final_ans+=text2[it2]
                it2+=1
            
            final_ans+=lcs[lcsPos]
            it1+=1
            it2+=1
            lcsPos+=1
        
        if it1<len(text1):
            final_ans+=text1[it1:]
        
        if it2<len(text2):
            final_ans+=text2[it2:]
        
        return final_ans


        return recur(0,0)
        
        
152159