Skip to problem
←

Alien Dictionary

Hard 0 attempts

Given an array of words claimed to be sorted in an unknown alphabet, infer an ordering of its letters. Return each letter that appears in the input exactly once. If several orders are possible, return any of them.

Compare words lexicographically: the first different character determines their order. If one word is a prefix of another, the shorter word must come first.

Return an empty string if the claimed order is impossible, including contradictory letter relationships or a longer word placed before its own prefix.

Function contract

Implement alienDictionary(words), where words is an array of strings in the proposed alien lexicographic order.

Output: A string containing each observed letter exactly once in a valid order, or "" if no order exists. Any valid order is accepted.

Example 1

Input
words = ["wrt","wrf","er","ett","rftt"]
Output
"wertf"

Example 2

Input
words = ["z","x"]
Output
"zx"

Example 3

Input
words = ["abc","ab"]
Output
""
Visual Aid
Letter order in example 1
wertf

Adjacent word comparisons give t → f, w → e, r → t, and e → r. Together they require the order wertf.

Constraints
  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of lowercase English letters
Topics

Topological Sort

Build a directed graph from adjacent word comparisons, then perform topological sort.

javascript
function alienDictionary(words) {
  const graph = new Map(), inDeg = new Map();
  for (const w of words) for (const c of w) { graph.set(c, new Set()); inDeg.set(c, 0); }
  for (let i = 0; i < words.length - 1; i++) {
    const [a, b] = [words[i], words[i+1]];
    const minLen = Math.min(a.length, b.length);
    if (a.length > b.length && a.slice(0, minLen) === b.slice(0, minLen)) return "";
    for (let j = 0; j < minLen; j++) {
      if (a[j] !== b[j]) {
        if (!graph.get(a[j]).has(b[j])) { graph.get(a[j]).add(b[j]); inDeg.set(b[j], inDeg.get(b[j])+1); }
        break;
      }
    }
  }
  const q = [...inDeg.keys()].filter(c => inDeg.get(c) === 0), res = [];
  let head = 0;
  while (head < q.length) {
    const c = q[head++]; res.push(c);
    for (const n of graph.get(c)) { inDeg.set(n, inDeg.get(n)-1); if (inDeg.get(n)===0) q.push(n); }
  }
  return res.length === inDeg.size ? res.join('') : "";
}

Time: O(C) where C = total chars | Space: O(U + min(U², N)) where U = unique characters and N = number of words

Loading discussion…

Saved in this browser only. Private to you.

JavaScript