> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Find the Shortest Superstring Python Solution

> Tested Python solution for LeetCode 943 with 57 pytest cases. Generate a practice environment with lcpy.

LeetCode 943, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [String](/catalog/topics/string), [Dynamic Programming](/catalog/topics/dynamic-programming), [Bit Manipulation](/catalog/topics/bit-manipulation), [Bitmask](/catalog/topics/bitmask), Hamiltonian Path. [View on LeetCode](https://leetcode.com/problems/find-the-shortest-superstring/description/).

Generate this problem as a practice environment: tested reference solution, 57 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 943   # by problem number
lcpy gen -s find_the_shortest_superstring   # by problem name
```

## Problem

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

### Examples

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

```
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**.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_the_shortest_superstring/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_the_shortest_superstring/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n^2 * 2^n) overlap precompute plus O(n^2 * 2^n) DP over masks
    # Space: O(n * 2^n) for the parent-tracking DP table
    def shortest_superstring(self, words: list[str]) -> str:
        n = len(words)
        if n == 1:
            return words[0]

        overlap = [[0] * n for _ in range(n)]
        for i in range(n):
            for j in range(n):
                if i != j:
                    a, b = words[i], words[j]
                    for k in range(min(len(a), len(b)), 0, -1):
                        if a.endswith(b[:k]):
                            overlap[i][j] = k
                            break

        size = 1 << n
        dp = [[0] * n for _ in range(size)]
        parent = [[-1] * n for _ in range(size)]
        for mask in range(1, size):
            for last in range(n):
                if not mask >> last & 1:
                    continue
                prev_mask = mask ^ (1 << last)
                if prev_mask == 0:
                    dp[mask][last] = len(words[last])
                    continue
                best_len = 10**9
                best_prev = -1
                for prev in range(n):
                    if prev_mask >> prev & 1:
                        cand = dp[prev_mask][prev] + len(words[last]) - overlap[prev][last]
                        if cand < best_len:
                            best_len = cand
                            best_prev = prev
                dp[mask][last] = best_len
                parent[mask][last] = best_prev

        full = size - 1
        last = min(range(n), key=lambda i: dp[full][i])
        order: list[int] = []
        mask = full
        while last != -1:
            order.append(last)
            prev = parent[mask][last]
            mask ^= 1 << last
            last = prev
        order.reverse()

        result = words[order[0]]
        for i in range(1, n):
            result += words[order[i]][overlap[order[i - 1]][order[i]] :]
        return result
```

## Complexity

| Time | Space |
| - | - |
| O(n^2 \* 2^n) overlap precompute plus O(n^2 \* 2^n) DP over masks | O(n \* 2^n) for the parent-tracking DP table |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.