-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalienDictionary.js
More file actions
54 lines (52 loc) · 1.42 KB
/
alienDictionary.js
File metadata and controls
54 lines (52 loc) · 1.42 KB
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
var alienOrder = function(words) {
let adj = new Map();
words.forEach(word => {
word.split('').forEach(l => adj.set(l, new Set()))
});
let order = new Array(adj.size);
//build adjacency list
let i=1;
while(i < words.length){
if(!getAdjacent(words[i-1], words[i])) return "";
i++;
}
// do dfs topological sort
let seen = new Set();
i = order.length-1;
let isCyclical = false;
adj.forEach((key) => {
if(isCyclical || i < 0 ) return false;
if(seen.has(key)) return;
this.history = new Set();
dfs(key);
})
return isCyclical ? "" : order.join('')
function dfs(key){
if(this.history.has(key)) {
isCyclical = true;
return false
}
if(seen.has(key)) return false;
this.history.add(key);
adj.get(key).forEach((val) => {
if(isCyclical) return false;
dfs(val);
});
seen.add(key);
this.history.delete(key);
order[i] = key;
i--;
}
function getAdjacent(w1, w2){
let l = 0;
let short = Math.min(w1.length, w2.length);
while(w1[l]==w2[l]){
if(l + 1 == short) break;
l++;
}
if(w1[l] == w2[l] && w1.length > w2.length) { return false }
if(w1[l] == w2[l] && w1.length <= w2.length){ return true }
adj.get(w1[l]).add(w2[l]);
return true;
};
};