Given words claimed to be lexicographically sorted, decide whether the letter order is unique, impossible, or ambiguous.
Medium6Topological sortGraphStringNo attempts yetTime limit2sMemory limit512 MBAlphabetizing a list of words is easy once you know the order of the letters. If one word is a prefix of another, the shorter word always comes first. For any other two words there is a first position where their letters differ, and the alphabet order of those two letters decides the order of the words.
Now turn the problem around. Given only a list of words that is claimed to be in lexicographic order, can you recover the order of the letters?
Comparing two neighboring words in the list gives one precedence relation between two letters. Any arrangement of the letters that satisfies every relation you collect is a candidate alphabet. If exactly one candidate exists, that arrangement is the answer.
The relations can contradict each other. A list that forces a before b and at the same time forces b before a is not sorted under any order of the letters.
The relations can also be too few. If the list never reveals which of two letters comes first, several different arrangements all explain the list.
The first line contains L and N, separated by a space. L is the last lowercase letter of this alphabet in English alphabetical order, with b≤L≤z, so every lowercase letter from a through L belongs to the alphabet. N is the number of strings in the list, with 1≤N≤1000.
Each of the next N lines contains one string, in the order the list places it. Each string has length between 1 and 1000 and uses only the lowercase letters from a through L. No string is given twice. Nothing guarantees that the list can be sorted at all.
If exactly one arrangement of the letters puts the list in lexicographic order, print that arrangement on one line. The arrangement uses every letter from a through L exactly once, including letters that never appear in the list.
If no such arrangement exists, print IMPOSSIBLE. If two or more exist, print AMBIGUOUS.