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

You are given a list of strings words from the alien language's dictionary. Now it is claimed that the strings in words are sorted lexicographically by the rules of this new language.

If this claim is incorrect, and the given arrangement of string in words cannot correspond to any order of letters, return "". Otherwise, return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new language's rules.

If there are multiple solutions, return any of them.

Input & Output

Example 1 — Basic Alien Dictionary
$ Input: words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
💡 Note: From "wrt" and "wrf", we get t->f. From "wrf" and "er", we get w->e. From "er" and "ett", we get r->t. From "ett" and "rftt", we get e->r. So the order is w->e->r->t->f, giving "wertf".
Example 2 — Simple Two Letters
$ Input: words = ["z","x"]
Output: "zx"
💡 Note: From "z" and "x", we get z comes before x in alien language ordering.
Example 3 — Invalid Dictionary
$ Input: words = ["abc","ab"]
Output: ""
💡 Note: "abc" cannot come before "ab" in any valid dictionary ordering since "abc" has "ab" as prefix but is longer.

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 100
  • words[i] consists of only lowercase English letters

Visualization

Tap to expand
INPUT DICTIONARYGRAPH BUILDINGALIEN ORDER"wrt""wrf""er""ett""rftt"Words in aliendictionary order1Compare adjacent words2Find first difference3Create directed edges4Topological sortwrt vs wrf: t comes before fwrf vs er: w comes before eer vs ett: r comes before tett vs rftt: e comes before rAlien Alphabetw e r t fValid ordering foundNo cycles detectedKey Insight:Adjacent words in the dictionary reveal letter precedence relationshipsTutorialsPoint - Alien Dictionary | Topological Sort
Asked in
Google 85 Facebook 72 Amazon 65 Microsoft 58
285.0K Views
High Frequency
~35 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen