Graphs Topological sort
457. Alien Dictionary
An alien language uses the lowercase English letters, but in an alphabetical order of its own that you do not
know. You are given words, a list of words in this language, sorted in its alphabetical order.
Return a string that holds every letter that appears in words, each exactly once, in an order under which
the list is sorted. If no order of the letters works, return the empty string "".
The list is sorted the way a dictionary is. Two words are compared letter by letter, and the first position where they differ decides: the word with the earlier letter there comes first. If one word ends before any difference, it is the start of the other word, and the shorter word comes first. Equal words can sit side by side.
Often several orders work, and any of them is correct. The result shows a valid order when the string you
return is one. An empty answer shows as "". Any other answer shows what is wrong with it, such as
the letter k is missing.
Example 1
Input: words = ["tor", "tom", "mrt", "mob", "or"]
"brtmo"Explanation: Neighbouring words give four rules: r before m, t before m, r before o, and m before o. The letter b is in
no rule, so it can go anywhere. "trbmo" is also correct.
Example 2
Input: words = ["sat", "sea", "seal", "se"]
""Explanation: "se" is the start of "seal", so in any order it comes before "seal". Here it comes after, and no
order of the letters can fix that.
Example 3
Input: words = ["xy", "yz", "zx", "xz"]
""Explanation: The neighbours say x comes before y, y before z, and z before x. These rules go round in a circle, so no order keeps all three.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ words.length ≤ 1051 ≤ words[i].length- The words together hold at most 106 letters.
words[i]consists of lowercase English letters.
Clarifying questions
What you would ask an interviewer before writing any code.