Skip to content
Decoder

Alien Dictionary

Hard

Problem

An alien language uses lowercase English letters in an unknown order. You get a list of its words, sorted in the alien alphabet's order. Return a string of every letter that appears, arranged in an order consistent with that sorting. If no order works (the list is contradictory or impossible), return "".

Words compare like a dictionary: the first position where two words differ decides, and if one word is a prefix of the other, the shorter word comes first. If more than one order fits, any of them is accepted; the tests here only use lists where exactly one order fits.

Example 1

Input
words = ["wrt", "wrf", "er", "ett", "rftt"]
Output
"wertf"

Example 2

Input
words = ["z", "x", "z"]
Output
""
Why
z before x and x before z

Example 3

Input
words = ["abc", "ab"]
Output
""
Why
a longer word cannot come before its prefix

Constraints

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] uses lowercase English letters only

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.