Ctrl K

Shortest Glued Chain

Medium
You get an array of non-empty words words. Gluing strings x and y means writing x followed by y, except that when the last letter of x equals the first letter of y, one of those two letters is dropped. For example, gluing ab and ba gives aba, while ab and cde give abcde. Start with the string words[0]. Then take the remaining words one by one, in order, and for each words[i] choose where it goes: at the end of the current string (glue the string, then the word) or at the front (glue the word, then the string). Return the smallest possible length of the string once every word has been glued on.
Example 1
words=['xy', 'zx'] → 3

Gluing zx in front makes the two xs meet at the seam, giving zxy of length 3. Gluing it at the back would give xyzx.

Example 2
words=['ab', 'bc', 'ca'] → 4

ab + bc = abc, then abc + ca = abca. Nothing shorter than 4 is possible.

Example 3
words=['k'] → 1

There is nothing to glue, so the answer is the length of the only word.

Constraints
  • 1 ≤ len(words) ≤ 1000
  • 1 ≤ len(words[i]) ≤ 50
  • Words consist of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSplit Into Dictionary Words MediumA Phrase on a Ticker Board MediumBit Strings on a Budget MediumWords Hidden in a Text MediumWord Growth Chain Medium
loading Python…
Input
words=['xy', 'zx']
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 88 tests on the server, hidden ones included.