Skip to content
BytePatterns

Alien Alphabet Order

HardGraphs#topological-sort#graph-from-constraints~40m

Problem

A recovered dictionary from an unknown language uses lowercase English letters, but in a different alphabetical order. Given its words, already sorted by that unknown order, return a string of every letter that appears, arranged in an order consistent with the dictionary. When several letters could come next, take the one that is earliest in the English alphabet, so the answer is unique. If no order fits the words, return an empty string. There are up to 100 words of up to 100 letters each.

Examples

Input:  words = ["wrt", "wrf", "er", "ett", "rftt"]
Output: "wertf"
Why:    the neighbouring pairs give t before f, w before e, r before t and e before r
Input:  words = ["z", "x", "z"]
Output: ""
Why:    z must come before x and x before z, a contradiction
Input:  words = ["abc", "ab"]
Output: ""
Why:    edge case, a word cannot come before its own prefix in any order

Hints

0 / 3

Stuck on the idea rather than the code? Topological Sort covers it.