Shortest Common Supersequence (SCS) šŸŽÆ

beginner
16 min

Shortest Common Supersequence (SCS) šŸŽÆ

Welcome to a fascinating journey into the realm of Data Structures and Algorithms! Today, we'll delve into the Shortest Common Supersequence (SCS), a crucial concept that helps us find a sequence common to two or more strings. Let's get started!

Introduction šŸ“

The Shortest Common Supersequence problem is about finding the shortest sequence that contains all the characters of two or more given sequences, without duplicating any characters. This problem is widely used in bioinformatics, text processing, and computer science.

Example šŸ“

Let's consider two strings: X = ABCDE and Y = ABDFA. The Shortest Common Supersequence for these two strings would be LCS(X, Y) = ABCDF.

Algorithm šŸ’”

The solution to the Shortest Common Supersequence problem can be achieved using Dynamic Programming with a Top-Down approach. Here's a simple step-by-step guide:

  1. Create a 2D matrix dp of size (len(X)+1) x (len(Y)+1).
  2. Initialize the first row and column with 0's.
  3. Iterate through the strings X and Y, and for each pair of indices, calculate the maximum of:
    • dp[i][j] (the length of the shortest common supersequence of X[0:i] and Y[0:j]),
    • dp[i-1][j-1] (the length of the shortest common supersequence of X[0:i-1] and Y[0:j-1]) plus 1 (if X[i] equals Y[j]),
    • min(dp[i][j-1], dp[i-1][j]) (if X[i] does not equal Y[j]).
  4. The answer is found in the bottom-right cell of the matrix, i.e., dp[len(X)][len(Y)].

Code Example āœ…

Here's a Python implementation of the Shortest Common Supersequence algorithm:

python
def shortest_common_supersequence(X, Y): len_X, len_Y = len(X), len(Y) dp = [[0 for _ in range(len_Y + 1)] for _ in range(len_X + 1)] for i in range(1, len_X + 1): for j in range(1, len_Y + 1): if X[i - 1] == Y[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) return ''.join(itertools.chain(*map(lambda row: row[-1], zip(*dp[len_X:][::-1]))))

Quiz šŸ’”

Quick Quiz
Question 1 of 1

What is the Shortest Common Supersequence (SCS) problem about?