Recover an alien alphabet from a sorted word list
Your task
Archaeologists found a dictionary in an alien language that uses the letters a to z, but in an unknown order. The words are sorted by that alphabet, the way an English dictionary is sorted by ours.
Write alien_order(words) that returns an order of the letters that fits the dictionary.
Input and output:
words: a list of 1 to 1,000 words in dictionary order, each 1 to 100 lowercase letters.- Returns a string that holds every letter appearing in
wordsexactly once, or the empty string when no order fits.
Rules:
- Dictionary order compares two words at the first position where they differ: the word with the earlier letter there comes first. If one word is the start of the other, the shorter word comes first.
- Only that first difference says anything about the alphabet. Equal words say nothing.
- Return the empty string if no order of the letters puts the words in the order given. This includes a word that comes before a shorter word it starts with.
- If several orders fit, return the one that comes first when the possible answers are compared letter by letter in ordinary
atozorder. - Letters that never appear in
wordsare not part of the answer.
Examples
alien_order(words: list[str]) -> strExample 1
Input
alien_order(["wrt", "wrf", "er", "ett", "rftt"])Output
"wertf"Example 2
Input
alien_order(["bc", "a"])Output
"bac"