Problem Description
Given three strings a, b, and c, find the shortest possible string that contains all three as substrings. If multiple such strings exist, return the lexicographically smallest one.
Key Insights
- Only three strings are involved, so we can try all permutations (only 6) to find the optimal ordering.
- Before merging, remove any string that is already a substring of another to potentially reduce work.
- Merging two strings greedily by maximizing the overlap between the suffix of the first and the prefix of the second can yield the shortest superstring for that pair.
- When two merged results have the same length, lexicographic comparison is used to choose the answer.
Space and Time Complexity
Time Complexity: O(1) in the context of permutation and merge checks since there are just 3 strings and each merge is O(n^2) with n at most 100. Space Complexity: O(n) where n is the maximum length of the strings (for storing merged results).
Solution
We first check if any of the three strings is contained in another; if yes, we can discard the contained string as it is redundant. Then, for each permutation of the remaining strings, we merge them in order using a helper merge function. This merge function checks if the second string is already a substring of the first (and returns the first in that case), or otherwise finds the maximum overlap of the suffix of the first with the prefix of the second and combines them accordingly. Finally, we update our best candidate based on the minimum length, and if lengths are equal, the lexicographically smallest string is chosen.