Alien Dictionary

Hard~35 min

There is a new alien language that uses the English lowercase letters. However, the order of the letters is unknown to you.

You are given a list of strings words from the alien language's dictionary, where the strings in words are sorted lexicographically by the rules of this new language.

Derive the order of letters in this language. If the order is invalid, return an empty string. If there are multiple valid orderings, return any of them.

Note: A string s is lexicographically smaller than a string t if at the first letter where they differ, the letter in s comes before the letter in t in the alien language. If the first min(s.length, t.length) letters are the same, then s is smaller only if s.length < t.length.

Examples

Example 1
Input: words = ["wrt", "wrf", "er", "ett", "rftt"]
Output: "wertf"
Explanation: From "wrt" vs "wrf": t < f. From "wrt" vs "er": w < e. From "er" vs "ett": r < t. From "ett" vs "rftt": e < r. So the order is w < e < r < t < f.
Example 2
Input: words = ["z", "x"]
Output: "zx"
Explanation: From "z" vs "x": z < x. The order is z < x.
Example 3
Input: words = ["z", "x", "z"]
Output: ""
Explanation: The order would require z < x and z > x, which is a contradiction (cycle).

Constraints

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of only lowercase English letters
  • Expected time complexity: O(V + E)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run