Alien Dictionary
Difficulty: Hard
An alien language uses English letters, possibly in a different order. You're given a list of its words, sorted by the alien alphabet's (unknown) order - the way an English dictionary is sorted a to z.
Return one valid ordering of the alien alphabet as a string, each letter once. If no ordering fits the word list, return an empty string. If several fit, return any of them.
Examples
Input: words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
Comparing consecutive words: wrt/wrf gives t before f, wrf/er gives w before e, er/ett gives r before t, ett/rftt gives e before r. Together these force the order w, e, r, t, f.
Input: words = ["z","x"]
Output: "zx"
The first word starts with z, the second with x, so z must come before x in this alphabet.
Input: words = ["z","x","z"]
Output: ""
z before x (from words 1-2) and x before z (from words 2-3) can't both be true, so no valid ordering exists.
Constraints
1 <= words.length <= 100
1 <= words[i].length <= 100
words[i] consists only of lowercase English letters.
Approach
Each pair of consecutive words gives one clue: at the first position where they differ, the earlier word's letter comes before the later word's. If there's no difference because one word is a prefix of the other, the shorter word must come first; otherwise it's a contradiction, since a word can never sort before its own prefix.
These clues form a directed graph where a -> b means "a comes before b." Any valid alphabet is a topological sort of it, found by repeatedly removing in-degree-zero nodes (Kahn's algorithm) or by a DFS that also detects cycles. A cycle means no valid ordering, so return an empty string. Letters that appear in the words but have no edges must still appear in the output.
Solutions
Build Graph + Kahn's Algorithm (BFS Topological Sort)
Collect every letter in the word list, and build a directed graph (adjacency list plus in-degree counts) from the clues between consecutive words.
Then run Kahn's algorithm. Queue every letter with in-degree zero (nothing known to come before it). Pop a letter, append it to the result, and decrement the in-degree of each letter it points to, queueing any that reach zero. If the result is missing letters, the graph had a cycle (or an unresolved tie), so return an empty string.
function alienOrder(words) {
const allLetters = new Set();
for (const word of words) {
for (const ch of word) allLetters.add(ch);
}
const graph = new Map();
const inDegree = new Map();
for (const ch of allLetters) {
graph.set(ch, new Set());
inDegree.set(ch, 0);
}
for (let i = 0; i < words.length - 1; i++) {
const first = words[i];
const second = words[i + 1];
const minLen = Math.min(first.length, second.length);
let foundDifference = false;
for (let j = 0; j < minLen; j++) {
if (first[j] !== second[j]) {
if (!graph.get(first[j]).has(second[j])) {
graph.get(first[j]).add(second[j]);
inDegree.set(second[j], inDegree.get(second[j]) + 1);
}
foundDifference = true;
break;
}
}
// "abc" before "ab" can never be valid - a word can't sort before its own prefix.
if (!foundDifference && first.length > second.length) {
return "";
}
}
const queue = [];
for (const ch of allLetters) {
if (inDegree.get(ch) === 0) queue.push(ch);
}
const order = [];
while (queue.length > 0) {
const ch = queue.shift();
order.push(ch);
for (const next of graph.get(ch)) {
inDegree.set(next, inDegree.get(next) - 1);
if (inDegree.get(next) === 0) queue.push(next);
}
}
return order.length === allLetters.size ? order.join("") : "";
}Time: O(C) where C is the total number of characters across all words: building the graph scans each word once, and the sort visits every letter and edge once · Space: O(1) for the graph and in-degree map, since there are at most 26 letters, plus O(C) used while scanning the words
DFS-Based Topological Sort with Cycle Detection
Build the same graph. Run a DFS from every letter, tracking each letter as unvisited, on the active path (visiting), or done (visited).
Append a letter to the result after all its outgoing edges are explored, so letters with nothing after them come first. Reaching a visiting letter means a cycle, so return an empty string. Reversing the append order gives a valid topological ordering.
function alienOrder(words) {
const allLetters = new Set();
for (const word of words) {
for (const ch of word) allLetters.add(ch);
}
const graph = new Map();
for (const ch of allLetters) graph.set(ch, new Set());
for (let i = 0; i < words.length - 1; i++) {
const first = words[i];
const second = words[i + 1];
const minLen = Math.min(first.length, second.length);
let foundDifference = false;
for (let j = 0; j < minLen; j++) {
if (first[j] !== second[j]) {
graph.get(first[j]).add(second[j]);
foundDifference = true;
break;
}
}
if (!foundDifference && first.length > second.length) {
return "";
}
}
const state = new Map(); // "visiting" | "visited"
const order = [];
let hasCycle = false;
function dfs(ch) {
if (hasCycle) return;
if (state.get(ch) === "visiting") {
hasCycle = true;
return;
}
if (state.get(ch) === "visited") return;
state.set(ch, "visiting");
for (const next of graph.get(ch)) {
dfs(next);
}
state.set(ch, "visited");
order.push(ch);
}
for (const ch of allLetters) {
if (state.get(ch) === undefined) dfs(ch);
}
if (hasCycle) return "";
return order.reverse().join("");
}Time: O(C) where C is the total number of characters across all words, for the same reasons as the BFS version · Space: O(1) for the graph and state map, since there are at most 26 letters, plus O(C) used while scanning the words