KatInterview

Reconstruct Alphabet Order from Sorted Vocabulary

Trees & GraphsAuto-graded · 25 test cases
MediumAuto-gradedTrees & Graphstrees-graphsheaps-sortingstrings

Last updated

Determine character precedence in an unfamiliar alphabet using a sorted list of terms, returning the lexicographically first valid character sequence or an empty string for invalid inputs.

Given a sequence of strings words sorted according to the rules of an unfamiliar alphabet, reconstruct the relative ordering of all characters present in the vocabulary.

If the input is logically inconsistent (for example, a string appears before a shorter prefix of itself, or there are circular ordering dependencies), return an empty string "".

If multiple valid character orderings exist, return the one that is alphabetically smallest when comparing the character sequences themselves using standard English alphabetical order.

Constraints

  • 1 <= len(words) <= 100
  • 1 <= len(words[i]) <= 100
  • words[i] contains only lowercase English letters.

Examples

Example 1

Input: find_alien_order(['wrt', 'wrf', 'er', 'ett', 'rftt'])

Output: 'wertf'

Example 2

Input: find_alien_order(['z', 'x', 'z'])

Output: ''

Example 3

Input: find_alien_order(['z', 'x'])

Output: 'zx'

Hints

Hint 1

Adjacent words in the sorted array provide the immediate ordering relationships between characters.

Hint 2

Watch out for edge cases where a longer word appears before its own prefix—this is invalid in standard lexicographical ordering.

Hint 3

Use Kahn's algorithm paired with a priority queue (min-heap) to build the ordering while breaking ties lexicographically.