codejump
HardPro challengePythonJavaScriptTypeScript

Graph — Alien Dictionary

Data StructuresGraphsTopological SortStrings

solve(words) — words is a list of words **sorted lexicographically by the rules
of an alien language** whose alphabet is made of lowercase English letters in an
unknown order. Return a string with the letters of that language in a valid order.

  • If the input is inconsistent (a cycle in the ordering, or a word followed by a

shorter word that is its own prefix, like "abc" then "ab"), return "".

  • If several orders are valid, return the lexicographically smallest one by the

normal English alphabet (whenever several letters are free, pick the smallest).

  • Only letters that appear in words are part of the alphabet.

Compare each pair of adjacent words: the first position where they differ gives
one rule a comes before b. Then topologically sort the letters.

Examples

solve(["wrt","wrf","er","ett","rftt"])  → "wertf"
solve(["z","x"])                        → "zx"
solve(["z","x","z"])                    → ""     // z < x and x < z
solve(["abc","ab"])                     → ""     // a longer word cannot precede its prefix
solve(["za","zb","ca","cb"])            → "abzc" // a < b and z < c; ties broken alphabetically

Sample tests

Test #1Classic example
Input: [["wrt","wrf","er","ett","rftt"]]
Output: "wertf"
Test #2Two single-letter words
Input: [["z","x"]]
Output: "zx"
Test #3Contradictory rules
Input: [["z","x","z"]]
Output: ""