Find the Shortest Superstring II - Problem
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.
Input & Output
Example 1 — Overlap Case
$
Input:
s1 = "abc", s2 = "bcd"
›
Output:
"abcd"
💡 Note:
The suffix "bc" of s1 overlaps with the prefix "bc" of s2, so we merge them as "abc" + "d" = "abcd"
Example 2 — Containment Case
$
Input:
s1 = "hello", s2 = "ell"
›
Output:
"hello"
💡 Note:
s2 "ell" is already contained in s1 "hello", so the shortest superstring is just "hello"
Example 3 — No Overlap
$
Input:
s1 = "cat", s2 = "dog"
›
Output:
"catdog"
💡 Note:
No overlap exists between the strings, so we concatenate them as "cat" + "dog" = "catdog"
Constraints
- 1 ≤ s1.length, s2.length ≤ 1000
- s1 and s2 consist of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two strings s1 and s2
2
Find Overlap
Check suffix-prefix overlaps
3
Merge
Create shortest superstring
Key Takeaway
🎯 Key Insight: Finding maximum overlap between string endings minimizes the total superstring length
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code