Word Game
Time limit2sMemory limit2048 MB
Given up to 5 lowercase words, merge them pairwise by overlapping suffix and prefix to get the shortest possible single word, breaking ties lexicographically, or output -1 if impossible.
- Level
Medium5 of 10
- Topics
- Brute force, String, String matching, Recursion
- Solved
- No attempts yet
Problem
On the Word Game show, Ashley has selected words and asks Brandon to combine them. Two words and can be combined if has a suffix of length that is a prefix of . The result of combining them is a new word made of concatenated with the last letters of . If there are multiple values of that are valid, any can be chosen.
Brandon must repeatedly take a pair of words from the list of words that can be combined, and replace them in the list with the combined word, until the list contains only a single word, and that word is as short as possible. If multiple final words of the same length are possible, Brandon must find the lexicographically first one.
Input
The first line of the input contains a single integer , the number of words to start out with.
The next lines each contain a single word in lowercase letters of length at most 5.
Output
Output the lexicographically first word of minimum length Brandon can come up with. If it is not possible to come up with a single word, output .