Alien Dictionary⚓︎
Description⚓︎
There is a new alien language that uses the English alphabet. However, the order of the letters is unknown to you.
You are given a list of strings words
from the alien language's dictionary. Now it is claimed that the strings in words
are sorted lexicographically by the rules of this new language.
A string
a
is lexicographically smaller than a stringb
if in the first position wherea
andb
differ, stringa
has a letter that appears earlier in the alien language than the corresponding letter inb
. If the firstmin(a.length, b.length)
characters do not differ, then the shorter string is the lexicographically smaller one.
If this claim is incorrect, and the given arrangement of string in words
cannot correspond to any order of letters, return ""
.
Otherwise, return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new language's rules. If there are multiple solutions, return any of them.
Example 1:
- Input:
words = ["wrt","wrf","er","ett","rftt"]
- Output:
"wertf"
Example 2:
- Input:
words = ["z","x"]
- Output:
"zx"
Example 3:
- Input:
words = ["z","x","z"]
- Output:
""
- Explanation:
The order is invalid, so return "".
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
consists of only lowercase English letters.
Solution⚓︎
- Time complexity: \(O(C)\), where \(C\) is the total length of all the words in the input list, added together;
- Space complexity: \(O\left( U+\min \left( U^2,N \right) \right) \approx O\left( 1 \right)\), where \(N\) is the total number of strings in the input list, and \(U\) is the total number of unique letters in the alien alphabet (in this case is \(26\) ).