Alien Dictionary

HardGraphs

An alien language writes with lowercase English letters, but orders them differently. You get a list of its words, already sorted the way its dictionary sorts them: by the first letter where two words differ, and a word before any longer word it is the start of.

Return a string that holds every letter used in the words exactly once, in an order that fits the list. When several orders fit, any of them is accepted.

If no order fits, return "". That happens when the list contradicts itself, or when a word comes before a shorter word that is its own start, such as "abc" before "ab".

Examples

Example 1
Input:  words = ["cab", "cad", "bd", "bda", "da"]
Output: "acbd"

cab before cad puts b before d, and cad before bd puts c before b. Nothing places a, so "cbda" or "cabd" are right too.

Example 2
Input:  words = ["ba", "ab", "bb"]
Output: ""

The first pair puts b before a and the second puts a before b, so no order fits.

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 100
  • Words use lowercase English letters only.

Stuck?

Hint 1

Only neighbors in the list tell you anything, and only at the first letter where they differ: that letter comes before the other. These rules are arrows between letters, and the answer is a topological order of them.

Hint 2

Collect the arrows (once each), then run Kahn’s algorithm from the letters nothing points to. If some letters never come out, the arrows loop and the answer is "". Check for a longer word listed before its own prefix before anything else.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur