-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path269-alien-dictionary.py
43 lines (40 loc) · 1.32 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
37
38
39
40
41
42
43
from collections import deque
class Solution:
def alienOrder(self, words: List[str]) -> str:
graph = {}
indegrees = {}
for word in words:
for c in word:
graph[c] = set()
indegrees[c] = 0
for i in range(1, len(words)):
w1 = words[i - 1]
w2 = words[i]
diff = False
for j in range(min(len(w1), len(w2))):
c1 = w1[j]
c2 = w2[j]
if c1 != c2:
if c2 not in graph[c1]:
graph[c1].add(c2)
indegrees[c2] += 1
diff = True
break
if not diff and len(w1) > len(w2):
return ''
queue = deque([])
for i, indegree in indegrees.items():
if indegree == 0:
queue.append(i)
res = []
while queue:
node = queue.popleft()
res.append(node)
for neighbor in graph[node]:
indegrees[neighbor] -= 1
if indegrees[neighbor] == 0:
queue.append(neighbor)
return ''.join(res) if len(res) == len(indegrees) else ''
# time O(nL)
# space O(nL), due to building graph
# using graph and kahn and topological sort