Shortest String That Contains Three Strings - Problem

Given three strings a, b, and c, your task is to find a string that has the minimum length and contains all three strings as substrings.

If there are multiple such strings, return the lexicographically smallest one.

Notes:

  • A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
  • A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case
$ Input: a = "abc", b = "bca", c = "cab"
Output: "abcab"
💡 Note: One optimal arrangement is abc + cab (overlapping 'c' and 'ab') to get "abcab". This contains all three strings: abc (0-2), bca (1-3), cab (2-4). Length is 5.
Example 2 — No Overlap
$ Input: a = "abc", b = "def", c = "ghi"
Output: "abcdefghi"
💡 Note: No overlaps possible between these strings, so we concatenate in lexicographical order: abc + def + ghi = "abcdefghi". Length is 9.
Example 3 — One String Contains Others
$ Input: a = "a", b = "aa", c = "aaa"
Output: "aaa"
💡 Note: String "aaa" already contains both "a" and "aa" as substrings, so it's the optimal superstring with length 3.

Constraints

  • 1 ≤ a.length, b.length, c.length ≤ 50
  • a, b, and c consist of lowercase English letters only

Visualization

Tap to expand
Shortest String That Contains Three StringsInput Strings:abcbcacabString AString BString CFind arrangement with maximum overlap:abcababc + cab with c overlapResult: "abcab" (length 5)
Understanding the Visualization
1
Input
Three strings: abc, bca, cab
2
Find Overlaps
Look for overlapping parts between strings
3
Output
Shortest superstring: abcab (length 5)
Key Takeaway
🎯 Key Insight: Try all arrangements and maximize overlaps to find the shortest superstring
Asked in
Google 35 Amazon 28 Microsoft 22
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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