LeetCode solutions

1170. Shortest Common Supersequence

My accepted Python solution to LeetCode problem 1170, Shortest Common Supersequence, running in 406ms.

  • Difficulty: Hard
  • Python
  • Runtime 406ms
  • Memory 42.3MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 406ms, memory 42.3MB, accepted 2026-01-02.

python
class Solution:
    def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
        m, n = len(str1), len(str2)
        
        # DP for LCS
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if str1[i - 1] == str2[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                else:
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
        
        # Backtrack to build shortest common supersequence
        result = []
        i, j = m, n
        while i > 0 and j > 0:
            if str1[i - 1] == str2[j - 1]:
                result.append(str1[i - 1])
                i -= 1
                j -= 1
            elif dp[i - 1][j] > dp[i][j - 1]:
                result.append(str1[i - 1])
                i -= 1
            else:
                result.append(str2[j - 1])
                j -= 1
        
        while i > 0:
            result.append(str1[i - 1])
            i -= 1
        while j > 0:
            result.append(str2[j - 1])
            j -= 1
        
        return ''.join(reversed(result))

Source