imashutosh51

Print Longest Common Subsequence

Mar 6th, 2026 (edited)
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. '''
  2. LCS variation: First find the LCS and populate the dp table as a prerequisite.
  3. Now we have to backtrack the direction of the LCS so we will go to the right bottom of the dp table. eg i=len(s1)-1, j=len(s2)-1 then check if s1[i]==s2[j], it means that character was part of your subsequence so add it into your answer then check the left value(i,j-1) and up value(i-1,j) and check which one is higher, and update the i and j in that direciton.
  4.  
  5. The "Up" neighbor: dp[i-1][j] (The score if you ignore the current character in text1)
  6. The "Left" neighbor: dp[i][j-1] (The score if you ignore the current character in text2)
  7.  
  8. Intution is that the LCS must have come in that direction.if up is bigger means we can get bigger LCS in the direction if we ignore ith character.Technically dp[i][j] stores the LCS of s1[:i] and s2[:j].
  9. If the numbers Up and Left are equal, it doesn't actually matter which way you go; both paths will lead to an LCS of the same length, just potentially a different string if multiple LCS exist.
  10. '''
  11.  
  12. def fun(str1,str2, n,m,dp):
  13.     if n<0 or m<0:
  14.         return 0
  15.     if dp[n][m]!=-1:
  16.         return dp[n][m]
  17.     take=0
  18.     if str1[n]==str2[m]:
  19.         dp[n][m]=1+fun(str1,str2,n-1,m-1,dp)
  20.     else:
  21.         dp[n][m]=max(fun(str1,str2,n-1,m,dp), fun(str1,str2,n,m-1,dp))
  22.     return dp[n][m]
  23.  
  24. class Solution:
  25.     def longestCommonSubsequence(self, text1: str, text2: str) -> int:
  26.         dp=[[-1]*len(text2) for _ in range(len(text1))]
  27.         ans=fun(text1,text2,len(text1)-1, len(text2)-1, dp)
  28.  
  29.         i=len(text1)-1
  30.         j=len(text2)-1
  31.         lca=''
  32.         while i>=0 and j>=0:
  33.             if text1[i]==text2[j]:
  34.                 lca+=text1[i]
  35.                 i-=1
  36.                 j-=1
  37.             else:
  38.                 up=dp[i-1][j] if i-1>=0 else 0
  39.                 left=dp[i][j-1] if j-1>=0 else 0
  40.                 if up>left:
  41.                     i-=1
  42.                 else:
  43.                     j-=1
  44.         print(''.join(reversed(lca)))
  45.  
  46.         return ans
  47.        
Advertisement
Add Comment
Please, Sign In to add comment