-
Notifications
You must be signed in to change notification settings - Fork 0
/
269-Alien_Dictionary.py
36 lines (31 loc) · 1.13 KB
/
269-Alien_Dictionary.py
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
class Solution:
def alienOrder(self, words: List[str]) -> str:
# step 0: unique letters
reverse_adj_list = { c: [] for word in words for c in word }
# step 1: edges
for first_w, second_w in zip(words, words[1:]):
for f, s in zip( first_w, second_w ):
if f!= s:
reverse_adj_list[s].append(f)
break
else:
# second word isn't a prefix of first word
if len(first_w) > len(second_w):
return ""
# step 2: DFS
seen = {}
output = []
def visist(node):
if node in seen:
return seen[node]
seen[node] = False
for next_node in reverse_adj_list[node]:
result = visist(next_node)
if not result:
return False
seen[node] = True
output.append(node)
return True
if not all( visist(node) for node in reverse_adj_list ):
return ""
return "".join(output)