You're given a list of words, all written in some unknown alien language, and you're told that the list is sorted in that language's dictionary order. From those words alone, infer the alphabet — the order of the letters that explains the sort. This is LeetCode 269 "Alien Dictionary". The output is a string of every distinct character used in the input, arranged so that the input's order is consistent with it.
The order is not always unique — many valid alphabets can explain the same word list — and your function may return any one of them. If the input is inconsistent (cyclic constraints, or a longer word appearing before its own prefix), return the empty string.
function alienOrder(words: string[]): string;
// LeetCode classic — one valid order is 'wertf'.
alienOrder(['wrt', 'wrf', 'er', 'ett', 'rftt']);
// → 'wertf' (or any other valid topological order over {w, e, r, t, f})
// A single word constrains nothing. Any permutation of its characters is valid.
alienOrder(['hello']);
// → e.g. 'helo' (or 'hloe', etc. — order across these four chars is unspecified)
// All-same words — only one distinct character, so only one possible result.
alienOrder(['z', 'z', 'z']);
// → 'z'
// Prefix violation: 'ab' is a prefix of 'abc', so 'abc' cannot come first.
alienOrder(['abc', 'ab']);
// → '' (impossible in any dictionary order)
// Cyclic constraint: z must come before x (from pair 1), then x must come before z (from pair 2).
alienOrder(['z', 'x', 'z']);
// → '' (the resulting graph has a cycle)
''.['abc', 'ab']), no dictionary order can explain that ordering. Return ''.''. A cycle means the input is self-contradictory.Unlock the solution & editor
Runnable editor + tests
Solve in the browser with instant Jest feedback.
Detailed solutions
Walkthroughs, edge cases, and complexity notes.
Multi-framework variants
React, Vue, Vanilla, Angular — same question, different stacks.