#2800
Shortest String That Contains Three Strings
MediumStringGreedyEnumerationString ManipulationPermutations
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n!) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n!)Space O(n)
The optimal approach leverages permutations and efficient merging of strings while ensuring overlaps are maximized. This reduces unnecessary computations and ensures we find the shortest and lexicographically smallest string efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Generate all permutations of the three strings a, b, and c.
- 2Step 2: For each permutation, calculate the merged string using maximum overlaps.
- 3Step 3: Track the shortest merged string and ensure it is lexicographically smallest in case of ties.
solution.py19 lines
1from itertools import permutations
2
3def merge_strings(s1, s2):
4 max_overlap = 0
5 for i in range(1, min(len(s1), len(s2)) + 1):
6 if s1[-i:] == s2[:i]:
7 max_overlap = i
8 return s1 + s2[max_overlap:]
9
10
11def shortest_superstring(a, b, c):
12 min_length = float('inf')
13 result = ''
14 for perm in permutations([a, b, c]):
15 merged = merge_strings(merge_strings(perm[0], perm[1]), perm[2])
16 if (len(merged) < min_length) or (len(merged) == min_length and merged < result):
17 min_length = len(merged)
18 result = merged
19 return resultℹ
Complexity note: The time complexity is O(n!) due to the permutations of the three strings, where n is the number of strings (3 in this case). The space complexity is O(n) for storing the merged strings.
- 1Permutations help explore all possible orders of strings.
- 2Maximizing overlaps reduces the length of the resulting string.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.