Alien Dictionary

50 min · alienOrder()

A book importer receives a catalog that's already alphabetized, but the alphabet key is missing. The order of the words is the only evidence you get.

You're given words, a list that claims to be sorted by an unknown ordering of lowercase English letters. Lexicographic order means dictionary-style order: the first different letter decides which word comes first, while a shorter word comes first when one word is an exact prefix of the other.

Recover the alien alphabet for every letter that appears. Return one string containing each appearing letter exactly once, from earliest to latest.

A few ground rules:

  • Return "" if the clues contain a cycle — a loop of requirements such as a before b and b before a.
  • Return "" when a longer word appears before its own prefix. A catalog that places "signal" before "sign" can't be sorted under any alphabet.
  • Include every appearing letter, even when it never creates a comparison on its own.
  • Every solvable input you'll receive determines one complete order.

Constraints

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 20
  • Every word contains only lowercase English letters.
  • The number of distinct appearing letters is k <= 10.
  • Whenever a valid order exists, it is unique; invalid inputs contain a cycle or a longer-word-before-prefix contradiction.

Hints

Listen to neighboring words

Compare each word with the one immediately after it. At their first different position, the letter from the earlier word must come before the letter from the later word. Characters after that position reveal nothing.

No difference can still be evidence

If every character matches through the shorter word, check the lengths. Shorter before longer is fine; longer before shorter is the invalid-prefix case.

Turn clues into a graph

Build a directed graph — letters are nodes and each arrow records "must come before." A topological sort is a listing that places every arrow's source before its destination. Kahn's algorithm builds one by repeatedly taking a letter whose indegree, the number of incoming arrows, is zero. Finishing early exposes a cycle.

Follow-up

How would you report that several alphabets fit the same words? In Kahn's algorithm, what does having two zero-indegree choices at once tell you?

Visible cases

Examples

Example 1

ready
Input
words = [
  "wrt",
  "wrf",
  "er",
  "ett",
  "rftt"
]
Expected
"wertf"
Why
the first differences force w < e < r < t < f

Example 2

ready
Input
words = [
  "z",
  "x"
]
Expected
"zx"
Why
z must appear before x

Example 3

ready
Input
words = [
  "abc",
  "ab"
]
Expected
""
Why
a longer word can't come before its own prefix

Interview signal

Asked at

AmazonGoogleMetaAirbnb
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite