imashutosh51

Shortest Common Supersequence

May 11th, 2026
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | None | 0 0
  1. class Solution:
  2.     def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
  3.         memo = {}
  4.  
  5.         def solve(i, j):
  6.             # Base Case: If one string is empty, return the rest of the other string
  7.             if i == len(str1): return str2[j:]
  8.             if j == len(str2): return str1[i:]
  9.            
  10.             # Check memoization table
  11.             if (i, j) in memo:
  12.                 return memo[(i, j)]
  13.            
  14.             # If characters match, I take it once and move forward in both
  15.             if str1[i] == str2[j]:
  16.                 res = str1[i] + solve(i + 1, j + 1)
  17.             else:
  18.                 # Option 1: Take character from str1
  19.                 option1 = str1[i] + solve(i + 1, j)
  20.                 # Option 2: Take character from str2
  21.                 option2 = str2[j] + solve(i, j + 1)
  22.                
  23.                 # Pick the shorter result
  24.                 if len(option1) < len(option2):
  25.                     res = option1
  26.                 else:
  27.                     res = option2
  28.            
  29.             memo[(i, j)] = res
  30.             return res
  31.  
  32.         return solve(0, 0)
Advertisement
Add Comment
Please, Sign In to add comment