Alien Dictionary
HardGraphs
An alien language uses lowercase English letters, but in an unknown alphabetical order. You are given a list words that is claimed to be sorted in that alien order. Words are compared the usual dictionary way: look at the first position where they differ, and the word with the earlier letter comes first; if one word is a prefix of the other, the shorter word comes first.
Return a string containing every distinct letter that appears in words, each exactly once, in an order under which words is sorted. Letters must not appear if they are not in words.
- If several orders are valid, return any one of them.
- If no order can make
wordssorted (the comparisons contradict each other, or a word appears before a shorter word that is its own prefix), return"".
Example 1
- Input:
- words = ["bca", "bcd", "ad", "dc", "dd"]
- Output:
- "bacd"
- Explanation
- Neighbouring words give
abefored(bca/bcd),bbeforea(bcd/ad),abeforedagain (ad/dc) andcbefored(dc/dd). Sob<a<dandc<d."bacd"works, and so do"bcad"and"cbad"; any of them is accepted.
Example 2
- Input:
- words = ["xy", "yz", "xz"]
- Output:
- ""
- Explanation
- The first pair says
xcomes beforey, but the second pair saysycomes beforex. That is a contradiction, so the answer is"".
Example 3
- Input:
- words = ["mango", "man"]
- Output:
- ""
- Explanation
manis a prefix ofmango, so it would have to come first in any alphabet. The list is not sorted under any order.
Constraints
1 <= words.length <= 1001 <= words[i].length <= 100words[i]contains only lowercase English letters