Alien Dictionary

Question (LC.269)

The new alien language uses [a-z]. But the order of the letter is unknown.

Given a list of nonempty words from the alien dictionary (where words are sorted), derive the order of letters in this alien language.

Example

Input: ["z", "x"]
Output: "zx"

There may be multiple valid order of letters, return any one of them is fine.

Input: ["wrt", "wrf", "er", "ett", "rftt"]
Output: "wertf"

If the order is invalid, return an empty string.

Input: ["z", "x", "z"]
Output: ""

You may assume that if a is a prefix of b, then a must appear before b in the given dictionary.

Input: ["z", "an"]
Output: "zan" (n cannot be a prefix of z by this rule)

Analysis

We can think of this as a way to linearize the dependencies.

Two challenges:

  1. How to infer the dependency? (draw edges)

    1. It turns out a one-to-one comparison is enough

    2. One-to-many comparison is an overkill because letters at the same position can form a chain. Otherwise, the different position does not produce the same dependency info.

  2. How to store the graph structure? (adj list)

    1. acyclic graph: {'w': ['e'], 'r': ['t'], 't': ['f'], 'f': [], 'e': ['r']}

    2. cyclic graph: {'z': ['x'], 'x': ['z']}

Code

Time Complexity

n = number of words

l = the length of the longest word

time:

building graph = O(l * n + l * l * n) + topo sort = O(V + E)

space:

graph = O(V + E) + visited = O(V) + on stack = O(V)

Reference

Alien Dictionary by Ethan Li

Last updated