Skip to content
BytePatterns

Build a Shortest Supersequence

HardDynamic Programming#string-dp#subsequence-dp~45m

Problem

Given two strings a and b, return a shortest string that contains both of them as subsequences, meaning each can be read from it left to right by skipping some characters. Several strings may share the shortest length; any one of them is accepted, and the examples show one. Either input may be empty.

Examples

Input:  a = "tile", b = "style"
Output: "stiyle"
Why:    length 6 = 4 + 5 - 3, since "tle" is shared and written once
Input:  a = "abac", b = "cab"
Output: "cabac"
Why:    "ab" is shared, so 4 + 3 - 2 = 5 characters are enough
Input:  a = "", b = "xyz"
Output: "xyz"
Why:    edge case, only b has to fit

Hints

0 / 3

Stuck on the idea rather than the code? Reading the Answer Back covers it.