SDE & MLE Prep

269. Alien Dictionary

Problem

words are sorted lexicographically in an alien language that uses lowercase English letters in an unknown order. Return a string of the letters that appear, in an order consistent with words (any valid order), or "" if the list is inconsistent.

Example: ["wrt","wrf","er","ett","rftt"] → "wertf"; ["z","x","z"] → ""

Constraints: note ["abc","ab"] is invalid: a word can't come after its own prefix.

Compare adjacent words: the first differing letters give an edge a → b. If a word is followed by its own proper prefix, the input is invalid. Topologically sort the letters (Kahn); a cycle → "".

wrt, wrf  -> t < f
wrf, er   -> w < e
er, ett   -> r < t
ett, rftt -> e < r          order: w e r t f

Complexity: O(total characters).

class Solution:
    def alienOrder(self, words: List[str]) -> str:
        g = {ch: set() for w in words for ch in w}
        indeg = {ch: 0 for ch in g}
        for a, b in zip(words, words[1:]):
            for x, y in zip(a, b):
                if x != y:
                    if y not in g[x]:
                        g[x].add(y)
                        indeg[y] += 1
                    break
            else:
                if len(a) > len(b):
                    return ""
        q = deque(sorted(ch for ch in indeg if indeg[ch] == 0))
        out = []
        while q:
            u = q.popleft()
            out.append(u)
            for v in sorted(g[u]):
                indeg[v] -= 1
                if indeg[v] == 0:
                    q.append(v)
        return "".join(out) if len(out) == len(g) else ""