Problem · String

Infer a Lexicographically Smallest Alien Alphabet

Learn this problem
HardMicrosoft logoMicrosoftFULLTIMEONSITE INTERVIEW
See Microsoft hiring insights

Problem statement

An alien language uses the lowercase English letters, but their order is unknown. You receive an array words sorted according to that language.

Infer a character order that is consistent with the dictionary. Include every distinct character that appears in words exactly once.

  • If several orders are valid, return the lexicographically smallest valid order.
  • If a longer word appears before its exact prefix, or the inferred precedence rules contain a cycle, return the empty string.

Function

alienOrder(words: String[]) → String

Examples

Example 1

words = ["wrt","wrf","er","ett","rftt"]return = "wertf"

The adjacent words imply w < e < r < t < f, so the order is unique.

Example 2

words = ["za","zb","ca","cb"]return = "abzc"

The rules require a < b and z < c; choosing the smallest available character at each step gives abzc.

Example 3

words = ["abc","ab"]return = ""

A longer word cannot precede its exact prefix in a valid sorted dictionary.

Constraints

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • Every word contains only lowercase English letters.
  • The total number of characters is at most 10^4.

More Microsoft problems

drafts saved locally
public String alienOrder(String[] words) {
    // Write your solution here.
}
words["wrt","wrf","er","ett","rftt"]
expected"wertf"
checking account