oneby7

2-D Dynamic Programming Bitmask DP

601. Find the Shortest Superstring

Hard

You are given a list of distinct lowercase words, words. Return the shortest string that contains every one of them.

A word is contained in a string when its letters appear there one after another, with nothing between them. Two words can share letters: when the end of one word is the start of the next, those letters are written once. For example, "tenorbit" contains both "tenor" and "orbit", which share or.

Often several shortest strings exist, and any of them is correct. When the string you return contains every word, the result shows its length, as a superstring of length 15. Otherwise it shows the first word it is missing, such as words[2] = "tenor" is not in the answer. Positions count from 0.

Example 1

Input: words = ["bitter", "terrace", "tenor", "orbit"]

Output: "tenorbitterrace"

Explanation: In the order tenor, orbit, bitter, terrace, each word shares letters with the next: or, then bit, then ter. That saves 8 of the 23 letters, and no order saves more.

Example 2

Input: words = ["kiwi", "plum", "fig"]

Output: "figplumkiwi"

Explanation: No word ends with letters that another word starts with, so nothing can be shared. All three words written one after another, in any order, is correct.

Example 3

Input: words = ["dad", "add"]

Output: "dadd"

Explanation: With dad first, the two words share ad, which gives 4 letters. With add first, they share only d, and addad has 5.

Check your understanding

Work out the answer for this input before you write any code.

words = ["baba", "cabab", "ababc"]

Constraints

  • 1 ≤ words.length ≤ 16
  • 1 ≤ words[i].length ≤ 20
  • words[i] consists of lowercase English letters.
  • The words are distinct, and no word is contained in another.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.