Shortest String That Contains Three Strings — LeetCode 2800 Python Solution

MediumGreedyStringEnumeration
Problem
#2800
Pattern
Greedy
Reading time
4 min

The 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.

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2800. Shortest String That Contains Three Strings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2800. Shortest String That Contains Three Strings?
LeetCode 2800. Shortest String That Contains Three Strings is rated Medium on LeetCode.
What is the time complexity of LeetCode 2800. Shortest String That Contains Three Strings?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2800. Shortest String That Contains Three Strings?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2800. Shortest String That Contains Three Strings cover?
LeetCode 2800. Shortest String That Contains Three Strings is tagged Greedy, String and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview