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
Find the Shortest Superstring II INPUT s1 = "abc" a b c s2 = "bcd" b c d Potential Overlap: "bc" s1 = "abc" s2 = "bcd" ALGORITHM STEPS 1 Find Suffix of s1 Check "abc", "bc", "c" 2 Match Prefix of s2 Check "bcd", "bc", "b" 3 Find Max Overlap "bc" matches (len=2) 4 Merge Strings s1 + s2[overlap:] Overlap Check Table Suffix Prefix Match "bc" "bc" OK "abc" + "d" = "abcd" Remove overlap "bc" from s2 FINAL RESULT Shortest Superstring: a b c d Only in s1 Overlap (shared) Only in s2 Output: "abcd" Verification: "abc" in "abcd" - OK "bcd" in "abcd" - OK Key Insight: The optimal approach finds the maximum overlap between the suffix of one string and the prefix of the other. By maximizing overlap, we minimize the total length. Check both directions (s1+s2 and s2+s1) for best result. Time Complexity: O(n*m) where n and m are lengths of s1 and s2. Space Complexity: O(n+m) for the result. TutorialsPoint - Find the Shortest Superstring II | Optimized - Find Maximum Overlap
Asked in
Google 25 Microsoft 20 Amazon 15
21.3K Views
Medium Frequency
~15 min Avg. Time
850 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