Alien Dictionary

hard

A new language uses the lowercase English letters but in an unknown order. You are given words, a list of words sorted according to this alien alphabet. Derive the order of the letters: return them as a string in the language's order. If several are valid, return the lexicographically smallest (by normal English order). If the input is inconsistent (a contradiction, or a word appearing before its own prefix), return an empty string.

Hints

Sorted words reveal order: compare each adjacent pair at their first differing letter.
Each such pair gives one precedence edge; topologically sort the letters.
Return '' if there's a cycle or a word appears before its own prefix.

Common doubts

Sorted order is decided at the first difference; letters after it tell you nothing about the pair.
If one word is a prefix of the previous, longer word (e.g. 'ab' after 'abc'), no alphabet can sort them that way — return ''.
'' signals an invalid/contradictory input; a one-letter result means the alphabet has one letter.

Interview follow-ups

Kahn's emits fewer letters than exist, or DFS finds a back edge among the constraints.
The premise breaks — you can't derive constraints from unsorted words.

Fun facts

  • LeetCode 269 — a topological sort disguised as reverse-engineering an alphabet.
  • The same 'infer order from comparisons' idea underlies version-precedence resolution.

Asked at

AmazonFacebookGoogle
Frequently Sometimes Occasionally
Example 1
Input: words = ["baa","abcd","abca","cab","cad"]
Output: "bdac"
Adjacent comparisons force b<d<a<c.
Example 2
Input: words = ["abc","ab"]
Output: ""
A word can't come before its own prefix — invalid.
Constraints

- 1 <= words.length <= 100 - 1 <= words[i].length <= 100 - words consist of lowercase letters

Solve this problem →