Talentd
FleetCode

943. Find the Shortest Superstring

Hard45.8% acceptance2 companies

Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them.

You may assume that no string in words is a substring of another string in words.

Example 1:

Input: words = ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be accepted.

Example 2:

Input: words = ["catg","ctaagt","gcta","ttca","atgcatc"]
Output: "gctaagttcatgcatc"

Constraints:

  • 1 <= words.length <= 12
  • 1 <= words[i].length <= 20
  • words[i] consists of lowercase English letters.
  • All the strings of words are unique.

Asked at 2 companies

26:31
Still stuck?Read 5 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def shortestSuperstring(self, words: List[str]) -> str:
3
Starter codePython 3Spaces: 4
Examples
Input
["alex","loves","leetcode"]
Input
["catg","ctaagt","gcta","ttca","atgcatc"]
Your code is saved on this device.Solution