from collections import defaultdict, deque
def find_order(words):
adjlist = defaultdict(list)
indegrees = defaultdict(int)
for i, word in enumerate(words[:-1]):
word2 = words[i + 1]
for c1, c2 in zip(word, word2):
# Note: zip ignores shorter word chars
if c1 != c2:
adjlist[c1].append(c2)
indegrees[c2] += 1
if c1 not in indegrees:
indegrees[c1] = 0
break # only process one difference
sources = deque([c for (c, deg) in indegrees.items() if deg == 0])
ordering = []
while sources:
cur_source = sources.popleft()
ordering.append(cur_source)
for child in adjlist[cur_source]:
indegrees[child] -= 1
if indegrees[child] == 0:
sources.append(child)
return "".join(ordering)
Type your question above this line.
Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/6610306698575872