Derive an unknown alphabet order from a sorted word list
A fan wiki is documenting the invented script of a fantasy game. The game ships a glossary that is sorted by the script’s own alphabet, but nobody knows that alphabet. Each glyph is stored as a single character. Implement deriveGlyphOrder(words), which recovers an alphabet from the sorted glossary, or reports that the glossary cannot be sorted under any alphabet.
deriveGlyphOrder(words) // => string | null
Words are compared the usual way, but with the unknown alphabet: find the first position where two words differ, and the word whose character comes first in the alphabet comes first. If one word is a prefix of the other, the shorter word comes first. Equal words can sit next to each other.
words, exactly once, in an order under which words is sorted.null when no alphabet fits. This happens when the ordering rules contradict each other (for example, they need a before b and b before a), or when a word is followed by a strict prefix of itself.''.'a' and 'A' are different glyphs.deriveGlyphOrder(['kar', 'kat', 'rak', 'rat', 'aor', 'tok', 'oak']);
// => 'krato'
// kar/kat: r before t kat/rak: k before r rak/rat: k before t
// rat/aor: r before a aor/tok: a before t tok/oak: t before o
deriveGlyphOrder(['xz', 'yq']);
// => 'qxyz'
// Only x before y is known. q, x, and z could each come first; q has the smallest code.
deriveGlyphOrder(['@#', '#@']);
// => '@#' (the rules win over character codes)
deriveGlyphOrder(['vel', 'lev', 'vel']);
// => null (v before l and l before v)
deriveGlyphOrder(['rune', 'run']);
// => null ('run' is a prefix of 'rune', so it would have to come first)
deriveGlyphOrder(['', 'b', 'b', 'ba']);
// => 'ab'
deriveGlyphOrder([]);
// => ''