KatInterview

Recover a Letter Ordering from a Sorted Word List

Trees & GraphsAuto-graded · 27 test cases
MediumAuto-gradedTrees & Graphstopological-sortgraphstrings

Last updated

Derive precedence constraints between letters from adjacent sorted words, then topologically sort them while detecting contradictions and invalid prefix orderings.

Recover a Letter Ordering from a Sorted Word List

A made-up language uses lowercase English letters, but its alphabet order is unknown. You are given a list of non-empty words that a dictionary of this language lists in sorted order, using ordinary lexicographic comparison under the unknown alphabet.

Decide whether some alphabet order could make the list correctly sorted. If one exists, return a string containing every distinct letter that appears in the words, arranged in an order that works. If none exists, return the empty string "".

Rules

  • Two words are compared left to right. The first position where they differ decides which word comes first.
  • If one word is a proper prefix of the other, the shorter word must come first. A list where a longer word comes directly before its own proper prefix (for example ["abc", "ab"]) cannot be valid.
  • Identical neighbouring words are fine and give no information.
  • Letters that have no constraints relating them to others must still appear in the output.
  • If more than one ordering is valid, returning any one of them is acceptable.
  • If the constraints contradict each other (for example, a must precede b and b must precede a), return "".

Input

  • words: a list of strings.

Output

  • A string with each distinct letter from words exactly once, in a valid alphabet order, or "" if no valid order exists.

Constraints

  • 1 <= len(words) <= 100
  • 1 <= len(words[i]) <= 100
  • Each word consists of lowercase English letters only.

Examples

Example 1

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

Output: 'wertf'

Example 2

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

Output: ''

Example 3

Input: derive_letter_order(['abc', 'ab'])

Output: ''

Hints

Hint 1

Only neighbouring words need to be compared. For each adjacent pair, the first position where they differ gives exactly one 'this letter comes before that letter' fact, and nothing after that position matters.

Hint 2

Treat each letter as a node and each fact as a directed edge. A valid alphabet is a topological order of this graph, and a cycle means the list is impossible.

Hint 3

Do not forget two traps: a longer word followed by its own prefix produces no differing character and must be rejected explicitly, and repeated identical edges must not be counted twice in the in-degree.