Editor

Alien Alphabet

#418 · Graphs · Advanced · 160 XP · about 35 min

Explorers found a dictionary of a language that uses the lowercase letters a to z, but in a different alphabetical order. The words in words are sorted by that order, the way a dictionary is: two words are compared at the first position where they differ, and a word comes before every longer word that starts with it.

Write alien_order(words) that returns the alien alphabet: a string holding every letter that appears in the words, each once, in an order under which words is sorted.

  • The words rarely settle the order of every pair of letters. When several alphabets fit, return the one that comes first in normal alphabetical order: whenever more than one letter could come next, take the one that is earliest from a to z.
  • If no order of the letters makes words sorted, return ''.

Examples

alien_order(['tea', 'ten', 'ant', 'nat', 'nap'])  # returns 'etanp'
alien_order(['cab', 'cba', 'bc'])  # returns 'acb'
alien_order(['abc', 'ab'])  # returns ''
alien_order(['x', 'y', 'x'])  # returns ''

In the first example the words show that a comes before n (from 'tea' and 'ten'), t before a, and t before p. Nothing in them says where e goes, so it takes the earliest place it can. In the third, a longer word comes before its own start, and in the last, x would have to come both before and after y.

Constraints

  • 1 to 5,000 words, each with 1 to 20 lowercase letters.
  • The same word can appear more than once in a row.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.