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 Containing Three Strings INPUT Three Input Strings a = a b c b = b c a c = c a b GOAL: Find shortest string containing all three (lexicographically smallest) ALGORITHM STEPS 1 Compute Overlaps Find max suffix-prefix match abc + bca: overlap "bc" = 2 bca + cab: overlap "ca" = 2 2 Try All Permutations 6 orderings: abc, acb, bac... 3 Merge with Overlaps Combine strings optimally a + b: abc + bca ---> "abca" (overlap bc) + cab ---> "abcab" 4 Select Best Result Shortest, then lex smallest Best candidates (len=5): "abcab", "bcabc", "cabca" Winner: "abcab" (lex first) FINAL RESULT Output String "abcab" Substring Verification a = "abc": [abc]ab - OK b = "bca": a[bca]b - OK c = "cab": ab[cab] - OK Length = 5 Minimum possible! Key Insight: Optimized Overlap Detection The optimal solution maximizes overlaps between strings. By checking all 6 permutations and using suffix-prefix matching, we find the merge order that produces the shortest result. For equal lengths, we select the lexicographically smallest string. Time complexity: O(n^2) where n = sum of string lengths. TutorialsPoint - Shortest String That Contains Three Strings | Optimized Overlap Detection
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