Find the Shortest Superstring II Problem
Description
LeetCode Problem 3571.
You are given two strings, s1 and s2. Return the shortest possible string that contains both s1 and s2 as substrings. If there are multiple valid answers, return any one of them.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s1 = "aba", s2 = "bab"
Output: "abab"
Explanation:
"abab" is the shortest string that contains both "aba" and "bab" as substrings.
Example 2:
Input: s1 = "aa", s2 = "aaa"
Output: "aaa"
Explanation:
"aa" is already contained within "aaa", so the shortest superstring is "aaa".
Constraints:
1 <= s1.length <= 1001 <= s2.length <= 100s1ands2consist of lowercase English letters only.
Solution
Approach: Try Every Overlap
Let s1 be the shorter string. If it already occurs inside s2, then s2 is the answer. Otherwise the shortest result glues the two strings with the largest possible overlap: for each i, check whether a suffix of s1 is a prefix of s2 (answer s1[:i] + s2) or a prefix of s1 is a suffix of s2 (answer s2 + s1[m-i:]), and return the first match found while the overlap shrinks from the longest. If nothing overlaps, return s1 + s2.
Complexity: time O(n^2), space O(n), where n is the longer length.
class Solution:
def shortestSuperstring(self, s1: str, s2: str) -> str:
m, n = len(s1), len(s2)
if m > n:
return self.shortestSuperstring(s2, s1)
if s1 in s2:
return s2
for i in range(m):
if s2.startswith(s1[i:]):
return s1[:i] + s2
if s2.endswith(s1[: m - i]):
return s2 + s1[m - i :]
return s1 + s2