Koolaidrain

Alien Dictionary

Jan 18th, 2018 (edited)
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. Input: words[] = {"baa", "abcd", "abca", "cab", "cad"} --> n words, k chars
  2. Output: Order of characters is 'b', 'd', 'a', 'c'
  3.  
  4. 1. graph of letters, run topSort on the resultant DAG. O(n + k) time, O(n + k) space
  5.  
  6. - main fn: build graph, then add all directed edges, then run topSort with kahn's algo.
  7.  
  8. from itertools import tee, izip
  9. from collections import deque
  10.  
  11. class Graph():
  12. def __init__(self, numNodes):
  13. self.nodes = {chr(ord('a')+i):[] for i in range(numNodes)]
  14. def addEdge(self, char1, char2):
  15. self.nodes[char1].append(char2)
  16.  
  17. def getPairs(iterable):
  18. a, b = tee(iterable)
  19. b.next()
  20. return izip(a, b)
  21.  
  22. # topological sort on graph using kahn's algo
  23. def topSort(g):
  24. inDegrees = {char:0 for char in g.keys()}
  25. for char, nbrs in g.items():
  26. inDegrees[char] = len(nbrs)
  27. queue = deque()
  28. ordering = []
  29. for char, inDegree in inDegrees.items():
  30. if inDegree == 0:
  31. queue.append(char)
  32. while queue:
  33. char = queue.popleft()
  34. ordering.append(char)
  35. for nbrChar in g[char]:
  36. inDegrees[nbrChar] -= 1
  37. if inDegrees[nbrChar] == 0:
  38. queue.append(nbrChar)
  39. if len(ordering) == len(g):
  40. return ordering
  41. else:
  42. return 'no valid ordering'
  43.  
  44. def getOrder(words, numChars):
  45. g = Graph(numChars)
  46. for edge in getPairs(words):
  47. g.addEdge(*edge)
  48. return topSort(g)
Advertisement
Add Comment
Please, Sign In to add comment