All problems

Problem 280

Alien Dictionary

Hard · 30 pts · Graph, Topological Sort, String

Problem

An alien language uses lowercase English letters, but in an unknown alphabetical order. You are given a list of its words, already sorted in that alien order. Find an order of all the letters that appear in the words that is consistent with the list. If several orders are valid, print the one that comes first in normal alphabetical order. If no order fits, which happens when the rules contradict each other or a word comes before its own prefix, print INVALID. Compare each pair of neighbouring words: the first position where they differ gives a rule "letter a comes before letter b". Then run a topological sort with a min-heap, so the smallest available letter is always chosen next.

Input

First line: integer N. Second line: N words.

Output

Print the letters in order as one string, or INVALID.

Constraints

1 <= N <= 100; 1 <= word length <= 100

Example input

5
wrt wrf er ett rftt

Example output

wertf

Explanation

wrt before wrf gives t before f, wrf before er gives w before e, er before ett gives r before t, and ett before rftt gives e before r. The only order that fits is w, e, r, t, f, so the answer is wertf.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Count Shortest Paths Next: Is Graph a Valid Tree