Find the Shortest Superstring II - Problem
Find the Shortest Superstring
You are given two strings
๐ฏ Goal: Create a superstring by finding the optimal way to combine two strings, potentially overlapping them to minimize the total length.
Example: If
Input: Two strings
Output: The shortest string containing both as substrings
Note: If multiple valid answers exist, return any one of them.
You are given two strings
s1 and s2. Your task is to find the shortest possible string that contains both input strings as substrings.๐ฏ Goal: Create a superstring by finding the optimal way to combine two strings, potentially overlapping them to minimize the total length.
Example: If
s1 = "abc" and s2 = "bcd", the shortest superstring is "abcd" (length 4) rather than "abcbcd" (length 6), because we can overlap the common part "bc".Input: Two strings
s1 and s2Output: The shortest string containing both as substrings
Note: If multiple valid answers exist, return any one of them.
Input & Output
example_1.py โ Basic Overlap
$
Input:
s1 = "abc", s2 = "bcd"
โบ
Output:
"abcd"
๐ก Note:
The strings overlap at 'bc'. We can merge them as 'a[bc]d' where [bc] is the shared part, resulting in 'abcd' with length 4 instead of 'abcbcd' with length 6.
example_2.py โ One Contains Other
$
Input:
s1 = "abc", s2 = "ab"
โบ
Output:
"abc"
๐ก Note:
Since 'ab' is already contained within 'abc' as a substring, the shortest superstring is just 'abc'.
example_3.py โ No Overlap
$
Input:
s1 = "hello", s2 = "world"
โบ
Output:
"helloworld"
๐ก Note:
There's no overlap between 'hello' and 'world', so we simply concatenate them. Both 'helloworld' and 'worldhello' have the same length, so either is valid.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Overlap
Find where the end of one string matches the beginning of another
2
Calculate Savings
Determine how many characters we can save by merging
3
Choose Best Merge
Select the combination that gives the shortest result
4
Construct Result
Build the final superstring using the optimal overlap
Key Takeaway
๐ฏ Key Insight: By finding overlaps between string endings and beginnings, we can merge strings efficiently to create the shortest possible superstring that contains both inputs.
Time & Space Complexity
Time Complexity
O(n ร m)
Where n and m are lengths of the strings. We need to check all possible overlaps between suffixes and prefixes
โ Linear Growth
Space Complexity
O(n + m)
Space for storing the result string
โก Linearithmic Space
Constraints
- 1 โค s1.length, s2.length โค 1000
- s1 and s2 consist of lowercase English letters
- Both strings are non-empty
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code