269 Alien Dictionary

1. Question

There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.

Example 1: Given the following words in dictionary,

[
  "wrt",
  "wrf",
  "er",
  "ett",
  "rftt"
]

The correct order is:"wertf".

Example 2: Given the following words in dictionary,

[
  "z",
  "x"
]

The correct order is:"zx".

Example 3: Given the following words in dictionary,

The order is invalid, so return"".

Note:

  1. You may assume all letters are in lowercase.

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

  3. If the order is invalid, return an empty string.

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

2. Implementation

(1) BFS

3. Time & Space Complexity

BFS:时间复杂度O(n * L), n为word的个数,L为每个word的平均长度, 空间复杂度O(k), k为不同的character个数

Last updated

Was this helpful?