[LeetCode] Alien Dictionary

269. Alien Dictionary

There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.

You are given a list of strings words from the alien language’s dictionary, where the strings in words are sorted lexicographically by the rules of this new language.

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 is no solution, return “”. If there are multiple solutions, return any of them.

A string s is lexicographically smaller than a string t if at the first letter where they differ, the letter in s comes before the letter in t in the alien language. If the first min(s.length, t.length) letters are the same, then s is smaller if and only if s.length < t.length.

  • Time : O(V + E + n)
  • Space : O(k)
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
class Solution {
unordered_map<char, set<char>> to;
unordered_map<char, int> from;

pair<char, char> compare(string& s1, string& s2) {
for(int i = 0; i < min(s1.length(), s2.length()); i++) {
if(s1[i] == s2[i]) continue;
return {s1[i], s2[i]};
}
return {'_','_'};
}

void insert(char be, char af) {
if(to[be].count(af) || be == '_') return;
to[be].insert(af);
from[af]++;
from[be] += 0;
}

public:
string alienOrder(vector<string>& words) {
for(int i = 0; i <words.size() - 1; i++) {
auto [before, after] = compare(words[i], words[i + 1]);
if(before == '_' and words[i].length() > words[i+1].length()) return"";
insert(before, after);

}

for(auto w : words)
for(auto ch : w)
from[ch] += 0;

string res = "";
queue<char> q;
for(auto [ch, v]: from) {
if(!v) q.push(ch);
}

while(!q.empty()) {
auto ch = q.front(); q.pop();
res += ch;
for(auto nxt : to[ch]) {
if(--from[nxt] == 0) q.push(nxt);
}
}

return res.length() == from.size() ? res : "";
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/16/PS/LeetCode/alien-dictionary/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.