Alien Dictionary
Problem
An unknown language uses lowercase Latin letters but sorts them in an order you do not know. You are given a list of words that is already sorted according to that language's alphabet. Recover a possible ordering of the letters that appear in the words. Return it as a string. If the given list is inconsistent with any ordering, return "". If several orderings are consistent, any one is acceptable.
- There are at most a few hundred words, each at most a few hundred characters.
- Every letter that appears in any word must appear exactly once in the output.
- Sorting rules match ordinary lexicographic comparison, including the rule that a string sorts before any longer string that has it as a prefix.
Examples
words = ["psu","psg","is","iuu","sguu"]→"pisug". Comparing adjacent words givesu < g,p < i,s < u,i < s; the only order consistent with all of them isp i s u g.words = ["m","k","m"]→"".m < kfrom the first pair andk < mfrom the second: a contradiction.words = ["xyz","xy"]→"". A longer word appears before its own prefix, which no alphabet permits.
Hints
- What does a single pair of adjacent words tell you? Only one fact, and only from one position.
- Collect all such facts as directed edges between letters. What structure do consistent facts form, and what does an inconsistency look like?
- Build a graph from the first differing character of each adjacent pair (watching for the prefix case), then topological sort; a cycle or an unsortable remainder means
"".
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Sign in with your email — no purchase — and this question opens in full, along with 12 others.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395