Editor

Shortest Superstring

#494 · Dynamic programming · Expert · 270 XP · about 55 min

A superstring of a list of words is a string that contains every word as a run of consecutive characters. Words may overlap inside it: "catapult" contains "cat", "tap" and "pult".

Write shortest_superstring_length(words) that returns the length of the shortest possible superstring.

Examples

shortest_superstring_length(["cat", "tap", "pult"])  # returns 8
shortest_superstring_length(["ab", "bc", "abc"])     # returns 3
shortest_superstring_length(["xyz"])                 # returns 3

In the second example "abc" already contains the other two words.

Constraints

  • 1 <= len(words) <= 12
  • Every word has 1 to 20 lowercase letters.
  • Words may repeat.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.