Skip to content

Commit

Permalink
Create 16. Alien Dictionary.py
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb authored Mar 3, 2024
1 parent 8248532 commit 08a675d
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions 07_Graph/16. Alien Dictionary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# https://www.geeksforgeeks.org/problems/alien-dictionary/1
# https://www.youtube.com/watch?v=6kTZYvNNyps

class Solution:
def findOrder(self,alien_dict, N, K):

adj = {char: set() for word in alien_dict for char in word}

for i in range(len(alien_dict) - 1):
w1, w2 = alien_dict[i], alien_dict[i + 1]
minLen = min(len(w1), len(w2))
if len(w1) > len(w2) and w1[:minLen] == w2[:minLen]:
return ""
for j in range(minLen):
if w1[j] != w2[j]:
adj[w1[j]].add(w2[j])
break

visited = {} # {char: bool} False visited, True current path
res = []

def dfs(char):
if char in visited:
return visited[char]

visited[char] = True

for neighChar in adj[char]:
if dfs(neighChar):
return True

visited[char] = False
res.append(char)

for char in adj:
if dfs(char):
return ""

res.reverse()
return "".join(res)


0 comments on commit 08a675d

Please sign in to comment.