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 as usual. The first position where two words differ decides, 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, 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 before ten puts a before n. The other pairs give t before a, t before c and a before c. No rule mentions e, so the smallest order starts with it: e, t, a, c, n.
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 #1

Test #2

Test #3

Argument

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

Expected Output

"etacn"