Recover an alien alphabet from a sorted word list

Write codeMedium30 minGoogle and Meta style

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 words exactly 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 a to z order.
  • Letters that never appear in words are not part of the answer.

Examples

alien_order(words: list[str]) -> str
Example 1
Inputalien_order(["wrt", "wrf", "er", "ett", "rftt"])
Output"wertf"
Example 2
Inputalien_order(["bc", "a"])
Output"bac"