There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

For example,
Given the following words in dictionary,

[
“wrt”,
“wrf”,
“er”,
“ett”,
“rftt”
]
The correct order is: “wertf”.

Note:
You may assume all letters are in lowercase.
If the order is invalid, return an empty string.
There may be multiple valid order of letters, return any one of them is fine.

O(mn) time, O(52) space, BFS solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public class Solution {
public String alienOrder(String[] words) {
if (words == null || words.length == 0) return null;
// the set of chars after this char, lexicographically
Map<Character, Set<Character>> after = new HashMap<>();
// the number of chars before this char
Map<Character, Integer> inDegree = new HashMap<>();
for (String s : words) {
for (char c : s.toCharArray()) {
inDegree.put(c, 0);
}
}

for (int i = 0; i < words.length - 1; i++) {
int cur = words[i].length();
int next = words[i + 1].length();
int length = Math.min(cur, next);
for (int j = 0; j < length; j++) {
char c1 = words[i].charAt(j);
char c2 = words[i + 1].charAt(j);
if (c1 != c2) {
Set<Character> set = after.get(c1);
if (set == null) {
set = new HashSet<Character>();
}
if (!set.contains(c2)) {
set.add(c2);
after.put(c1, set);
inDegree.put(c2, inDegree.get(c2) + 1);
}
break; // no need to check the following chars as it's useless
}
}
}

Queue<Character> queue = new LinkedList();
StringBuilder sb = new StringBuilder();
for (char c : inDegree.keySet()) {
if (inDegree.get(c) == 0) {
queue.add(c);
}
}
// remove the chars without indegree = 0
while (! queue.isEmpty()) {
char c = queue.poll();
sb.append(c);
if (after.containsKey(c)) {
for (char next : after.get(c)) {
inDegree.put(next, inDegree.get(next) - 1);
if (inDegree.get(next) == 0) {
queue.add(next);
}
}
}
}
// invalid order
if (sb.length() != inDegree.size()) return "";
return sb.toString();
}
}