Under construction

Still being built. Things may change

Word Game

Time limit2sMemory limit2048 MB

Summary
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 nn words and asks Brandon to combine them. Two words ss and tt can be combined if ss has a suffix of length k>0k > 0 that is a prefix of tt. The result of combining them is a new word made of ss concatenated with the last ∣t∣−k|t|-k letters of tt. If there are multiple values of kk 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 nn (1≤n≤5)(1 \le n \le 5), the number of words to start out with.

The next nn 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 −1-1.

Examples3

  1. Example 1

    Input
    2
    aba
    bab
    
    Expected output
    abab
    
  2. Example 2

    Input
    3
    ab
    bc
    ca
    
    Expected output
    abca
    
  3. Example 3

    Input
    2
    x
    y
    
    Expected output
    -1