From 08a675d7b0cf98ff2362818e3f0a4aaad20af1f4 Mon Sep 17 00:00:00 2001 From: Samir Paul <77569653+SamirPaulb@users.noreply.github.com> Date: Sun, 3 Mar 2024 11:58:00 +0530 Subject: [PATCH] Create 16. Alien Dictionary.py --- 07_Graph/16. Alien Dictionary.py | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 07_Graph/16. Alien Dictionary.py diff --git a/07_Graph/16. Alien Dictionary.py b/07_Graph/16. Alien Dictionary.py new file mode 100644 index 00000000..f7859a53 --- /dev/null +++ b/07_Graph/16. Alien Dictionary.py @@ -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) + +