Find the Shortest Superstring II - Problem
Find the Shortest Superstring

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 s2
Output: 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
ABCDEDEFGHDEOverlap Found!ABCDEFGHShortest SuperstringLength: 8(vs 10 without overlap)
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n + m)

Space for storing the result string

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค s1.length, s2.length โ‰ค 1000
  • s1 and s2 consist of lowercase English letters
  • Both strings are non-empty
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
31.0K Views
Medium Frequency
~15 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen