Menu
CoddyTech

Alien Dictionary

A list of words is sorted in an alphabet you do not know: the 26 lowercase English letters in some secret order. Words compare the usual way. The first position where two words differ decides, by which of the two letters comes first in the alphabet, and when one word is the start of the other, the shorter word comes first.

Return the letters that appear in the words, as one string in alphabet order. When several orders fit the list, return the one that comes first in ordinary dictionary order. When no order fits, return "invalid".

Function

alienOrder(words: string-array) → string
wordsstring-array
the words, sorted in the unknown alphabet
Returnsstring
the letters in the smallest order that fits, or "invalid"

Constraints

  • 1 ≤ words.length ≤ 5000
  • 1 ≤ words[i].length ≤ 10
  • Every word contains only lowercase English letters.
  • The same word may appear more than once.

Examples

Input
words = ["tea", "ten", "ate", "act", "cat"]
Output
"etacn"
Explanation
tea and ten first differ at a and n, so a comes before n. The other pairs give t before a, t before c and a before c. No rule mentions e, so the smallest order puts it first, then t, then a, then c and n, which are both free by then, with c first.

lock icon+20 hidden tests on Submit

challenge icon

Follow-up

How would you tell whether the fitting order is the only one?

Reset code
def alienOrder(words):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

words = ["tea", "ten", "ate", "act", "cat"]

Expected

"etacn"