Staff

Alien Dictionary

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

You are given an array of strings words, where the words are sorted lexicographically according to the rules of this alien language. Return a string containing the letters of the alien alphabet in a valid order.

If there is more than one valid order, return any of them. If there is no valid ordering, return an empty string "".

A string a is lexicographically smaller than a string b if, at the first position where they differ, the character in a comes before the character in b in the alien alphabet. If the first min(a.length, b.length) characters are the same, then the shorter string is smaller.

You must include every unique character that appears in words exactly once in the returned ordering.

Example 1
Inputwords = ["wrt","wrf","er","ett","rftt"]
Output"wertf"
The sorted words imply the ordering constraints w < e, e < r, r < t, and t < f, so wertf is valid.
Example 2
Inputwords = ["z","x","z"]
Output""
The constraints imply both z < x and x < z, forming a cycle, so no valid alphabet order exists.

Constraints

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

Asked at 16 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate