Alien Dictionary
1 approach, code in every language
Problem description
You are given a list of words written in an alien language. Within this language the letters are drawn from the usual lowercase English alphabet, but their relative order is unknown.
The words are provided in an order that is lexicographically sorted according to the rules of this alien language. Using only that ordering information, determine a possible sequence of the distinct letters that appear, from smallest to largest.
Return any valid ordering as a string. If no consistent ordering exists, return an empty string. If several orderings are valid, returning any one of them is acceptable.
Example 1
Input: words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
Comparing neighbors yields t before f, w before e, r before t, and e before r, which chains into the order w, e, r, t, f.
Example 2
Input: words = ["abc","ab"]
Output: ""
A longer word appears before one of its own prefixes, which can never happen in a valid sorted list, so no ordering exists.
Constraints
1 <= words.length <= 1001 <= words[i].length <= 100words[i] consists of only lowercase English letters.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Lost Collation Order is our own problem on the technique behind Alien Dictionary: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free