Shortest String That Contains Three Strings Problem
Description
LeetCode Problem 2800.
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.
Return a string denoting the answer to the problem.
Notes
- A string
ais lexicographically smaller than a stringb(of the same length) if in the first position whereaandbdiffer, stringahas a letter that appears earlier in the alphabet than the corresponding letter inb. - A substring is a contiguous sequence of characters within a string.
Example 1:
Input: a = "abc", b = "bca", c = "aaa"
Output: "aaabca"
Explanation: We show that "aaabca" contains all the given strings: a = ans[2...4], b = ans[3..5], c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and "aaabca" is the lexicographically smallest one.
Example 2:
Input: a = "ab", b = "ba", c = "aba"
Output: "aba"
Explanation: We show that the string "aba" contains all the given strings: a = ans[0..1], b = ans[1..2], c = ans[0..2]. Since the length of c is 3, the length of the resulting string would be at least 3. It can be shown that "aba" is the lexicographically smallest one.
Constraints:
1 <= a.length, b.length, c.length <= 100a,b,cconsist only of lowercase English letters.
Solution
Approach: Enumerate Orders + Merge
Try all 6 orders of the three strings. To merge two strings s and t: if one contains the other, keep the longer one; otherwise find the longest suffix of s that is also a prefix of t, and glue t on after that overlap. Merge the first two, then merge the result with the third. Among the 6 results keep the shortest, breaking ties by lexicographic order.
Complexity: O(L^2) time and O(L) space, where L is the maximum length of the three strings.
from itertools import permutations
class Solution:
def minimumString(self, a: str, b: str, c: str) -> str:
def f(s: str, t: str) -> str:
if s in t:
return t
if t in s:
return s
m, n = len(s), len(t)
for i in range(min(m, n), 0, -1):
if s[-i:] == t[:i]:
return s + t[i:]
return s + t
ans = ""
for a, b, c in permutations((a, b, c)):
s = f(f(a, b), c)
if ans == "" or len(s) < len(ans) or (len(s) == len(ans) and s < ans):
ans = s
return ans