Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 1092 Shortest Common Supersequence - Walkthrough

Building from LCS

Shortest Common Supersequence contains both strings as subsequences. Length = m+nLCS lengthm + n - \text{LCS length}. To construct: trace the LCS path.

Include LCS characters once, non-LCS characters from both strings. Example: s1="abac"s_1 = \text{"abac"}, s2="cab"s_2 = \text{"cab"}. LCS = "ab" (length 2). SCS length = 4+32=54 + 3 - 2 = 5. SCS = "cabac". Construction: walk the DP table. When on diagonal (LCS char), include once. When going up/left, include the skipped char.