Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the alien-dictionary letter order from a sorted list of words (Kahn's algorithm, ties alphabetical).

Problem: Return the alien-dictionary letter order from a sorted list of words (Kahn's algorithm, ties alphabetical).
import heapq
def alien(words):
    letters = sorted(set(''.join(words)))
    adj = {c: set() for c in letters}; indeg = {c: 0 for c in letters}
    for a, b in zip(words, words[1:]):
        for x, y in zip(a, b):
            if x != y:
                if y not in adj[x]: adj[x].add(y); indeg[y] += 1
                break
        else:
            if len(a) > len(b): return ''
    h = [c for c in letters if indeg[c] == 0]; heapq.heapify(h); out = ''
    while h:
        c = heapq.heappop(h); out += c
        for d in sorted(adj[c]):
            indeg[d] -= 1
            if indeg[d] == 0: heapq.heappush(h, d)
    return out if len(out) == len(letters) else ''
print(alien(["wrt", "wrf", "er", "ett", "rftt"]), repr(alien(["abc", "ab"])))
What is printed?
  1. A. wertf ''
  2. B. wertf 'abc'
  3. C. werft ''
  4. D. fwert ''

Correct answer: A. wertf ''

Each adjacent pair of words gives one constraint from its first differing letter: t < f, w < e, r < t, e < r. Topological order: w, e, r, t, f. If a longer word comes before its own prefix ("abc" before "ab"), the input is invalid → ''. O(total characters).

More Coding Interview Problems questions

Exams that ask this topic