Overview
A supersequence contains both strings. To make it the *shortest* possible, we must reuse as many characters as possible. What characters can be reused? The characters in their LCS!
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Find the shortest string that has both given strings as subsequences. It's intimately tied to finding the Longest Common Subsequence (LCS).
A supersequence contains both strings. To make it the *shortest* possible, we must reuse as many characters as possible. What characters can be reused? The characters in their LCS!
The length of the SCS is exactly: `Length(S1) + Length(S2) - Length(LCS)`. We subtract the LCS because those characters are shared and only need to be written once.
We trace back through the LCS DP table. If characters match, we add it to our result ONCE. If they don't match, we add the character from the string we are "dropping" and move towards the larger DP value.
If we hit the edge of the DP table (`i=0` or `j=0`), we just append whatever is left of the other string, because we must include all characters to form a valid supersequence.
| S1 \ S2 | "" | c | a | b |
|---|---|---|---|---|
| "" | 0 | 0 | 0 | 0 |
| a | 0 | 0 | 1 | 1 |
| b | 0 | 0 | 1 | 2 |
| a | 0 | 0 | 2 | 2 |
| c | 0 | 1 | 2 | 2 |