Skip to content

Instantly share code, notes, and snippets.

@leonmak
Created January 30, 2019 07:58
Show Gist options
  • Save leonmak/ba86ba425ebad9aaf207d5aa37af25e2 to your computer and use it in GitHub Desktop.
Save leonmak/ba86ba425ebad9aaf207d5aa37af25e2 to your computer and use it in GitHub Desktop.
269. Alien Dictionary
from collections import defaultdict
class Solution(object):
def alienOrder(self, words):
"""
:type words: List[str]
:rtype: str
"""
graph = defaultdict(list)
# build graph
for w1, w2 in zip(words, words[1:]):
for a, b in zip(w1, w2):
# add first diff char
# exclude single char
if a != b:
graph[a].append(b)
break
# toposort graph
visited = set()
stack = []
def topo_dfs(node, path):
if node in visited:
return
visited.add(node)
path.add(node)
for nei in graph[node]:
if nei in path or topo_dfs(nei, path):
return True
stack.insert(0, node)
path.remove(node)
chars = set()
for w in words:
for c in w:
chars.add(c)
for c in chars:
if topo_dfs(c, set()):
return ''
return ''.join(stack)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment