Skip to content

Commit 422041c

Browse files
committed
Alien Dictionary
1 parent 2e98399 commit 422041c

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

0269_alienDictionary.js

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* @param {string[]} words Array of strings.
3+
* @return {string} String containing letters in order for alien language.
4+
* @summary Alien Dictionary {@link https://leetcode.com/problems/alien-dictionary/}
5+
* @description Given a list of words in alien dictionary which are sorted by rules of the language, return the order of letters in the language.
6+
* Space O(1) - store number of relations and at mosat unique records for number of unique chars.
7+
* Time O(n) - where n is the length of all of the words combined.
8+
*/
9+
const alienOrder = words => {
10+
const adjList = {};
11+
const counts = {};
12+
13+
for (let i = 0; i < words.length; i++) {
14+
const word = words[i];
15+
for (let j = 0; j < word.length; j++) {
16+
const char = word[j];
17+
18+
adjList[char] = [];
19+
counts[char] = 0;
20+
}
21+
}
22+
23+
for (let i = 0; i < words.length - 1; i++) {
24+
const w1 = words[i];
25+
const w2 = words[i + 1];
26+
27+
if (w1.length > w2.length && !w1.indexOf(w2)) {
28+
return '';
29+
}
30+
31+
for (let j = 0; j < Math.min(w1.length, w2.length); j++) {
32+
const c1 = w1[j];
33+
const c2 = w2[j];
34+
if (c1 !== c2) {
35+
adjList[w1[j]].push(w2[j]);
36+
counts[w2[j]]++;
37+
break;
38+
}
39+
}
40+
}
41+
42+
const answer = [];
43+
const queue = [];
44+
45+
Object.keys(counts).forEach(char => {
46+
if (!counts[char]) queue.push(char);
47+
});
48+
49+
while (queue.length) {
50+
const char = queue.pop();
51+
answer.push(char);
52+
53+
(adjList[char] || []).forEach(adjacent => {
54+
counts[adjacent]--;
55+
if (!counts[adjacent]) queue.unshift(adjacent);
56+
});
57+
}
58+
59+
return answer.length < Object.keys(counts).length ? '' : answer.join('');
60+
};

0 commit comments

Comments
 (0)