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.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.
words=['ab', 'bc', 'ca'] → 4
ab + bc = abc, then abc + ca = abca. Nothing shorter than 4 is possible.
words=['k'] → 1
There is nothing to glue, so the answer is the length of the only word.
words=['xy', 'zx']
3
Run checks the first 3 tests in your browser. Submit checks all 88 tests on the server, hidden ones included.