sagelearnai

Alien Dictionary

Difficulty: Hard · Pattern: Graphs (BFS / DFS) · LeetCode #269

An alien language uses lowercase English letters in an unknown order. You get a list of words sorted in that language. Return a string of all the unique letters in a valid order, or "" if the input is inconsistent. If several orders are valid, any one is accepted; the tests list all of them.

Examples

text
["wrt","wrf","er","ett","rftt"]  →  "wertf"
["z","x"]                        →  "zx"
["z","x","z"]                    →  ""     (z<x and x<z: a cycle)
["abc","ab"]                     →  ""     (a longer word can't come before its own prefix)

Hints

  1. Compare adjacent words only. The first position where they differ gives one ordering constraint a < b. Nothing after that position tells you anything.
  2. Then it's a topological sort over the letters. Include letters that have no constraints.
  3. Edge case: if w1 is longer than w2 and w2 is a prefix of w1, the input is invalid.

Approach

  1. Add every letter that appears as a node.
  2. For each adjacent pair (w1, w2), find the first j with w1[j] != w2[j] and add the edge w1[j] → w2[j], then stop. If there's no difference and len(w1) > len(w2), return "".
  3. Kahn's BFS topological sort. If the output covers fewer letters than exist, there's a cycle, so return "".

Pitfalls interviewers look for: comparing non-adjacent words (unnecessary), continuing past the first difference (wrong), forgetting isolated letters, and the prefix case.

Complexity

Time: O(C), the total characters across all words. Space: O(1) beyond that, since there are at most 26 letters and 26² edges.

Python solution
from collections import deque

def alienOrder(words):
    adj = {c: set() for w in words for c in w}
    indeg = {c: 0 for c in adj}
    for w1, w2 in zip(words, words[1:]):
        for a, b in zip(w1, w2):
            if a != b:
                if b not in adj[a]:
                    adj[a].add(b)
                    indeg[b] += 1
                break
        else:
            if len(w1) > len(w2):
                return ""
    q = deque(sorted(c for c in indeg if indeg[c] == 0))
    out = []
    while q:
        c = q.popleft()
        out.append(c)
        for d in sorted(adj[c]):
            indeg[d] -= 1
            if indeg[d] == 0:
                q.append(d)
    return ''.join(out) if len(out) == len(adj) else ""
JavaScript solution
function alienOrder(words) {
  const adj = new Map(), indeg = new Map();
  for (const w of words) for (const c of w) if (!adj.has(c)) { adj.set(c, new Set()); indeg.set(c, 0); }
  for (let i = 0; i + 1 < words.length; i++) {
    const w1 = words[i], w2 = words[i + 1];
    let j = 0;
    while (j < w1.length && j < w2.length && w1[j] === w2[j]) j++;
    if (j < w1.length && j < w2.length) {
      if (!adj.get(w1[j]).has(w2[j])) { adj.get(w1[j]).add(w2[j]); indeg.set(w2[j], indeg.get(w2[j]) + 1); }
    } else if (w1.length > w2.length) return '';
  }
  const q = [...indeg.keys()].filter((c) => indeg.get(c) === 0).sort();
  for (let h = 0; h < q.length; h++) for (const d of [...adj.get(q[h])].sort()) { indeg.set(d, indeg.get(d) - 1); if (indeg.get(d) === 0) q.push(d); }
  return q.length === adj.size ? q.join('') : '';
}