There is a new alien language which uses the English alphabet. However, the order among the letters is unknown to you.
You are given a list of strings words from the alien language, and your task is to determine the order of the letters in this language.
Return a string of the letters in the correct order. If there is no valid ordering, return "". If there are multiple valid orderings, return any of them.
Example 1:
Input: words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
Example 2:
Input: words = ["z","x"]
Output: "zx"
Example 3:
Input: words = ["z","x","z"]
Output: ""
Explanation: The order is invalid, so return "".
Constraints:
1 <= words.length <= 1001 <= words[i].length <= 100words[i] consists of lowercase English letters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a list of words from a strange language and you need to figure out the correct order of the alphabet. The brute force approach involves guessing every possible ordering of all the letters in the alphabet and checking if all the given words follow that guessed order.
Here's how the algorithm would work step-by-step:
import itertools
def alien_order(words):
unique_letters = sorted(list(set(''.join(words))))
# We generate all permutations to explore every possible alphabet ordering systematically
for candidate_order in itertools.permutations(unique_letters):
alphabet_position = {char: index for index, char in enumerate(candidate_order)}
is_valid_order = True
for first_index in range(len(words) - 1):
current_word = words[first_index]
next_word = words[first_index + 1]
minimum_length = min(len(current_word), len(next_word))
has_prefix = True
for char_index in range(minimum_length):
current_char = current_word[char_index]
next_char = next_word[char_index]
if current_char != next_char:
if alphabet_position[current_char] > alphabet_position[next_char]:
is_valid_order = False
has_prefix = False
break
# We check prefix rules to ensure longer words do not incorrectly precede their prefixes
if has_prefix and len(current_word) > len(next_word):
is_valid_order = False
if not is_valid_order:
break
# We return the first valid sequence found since it satisfies all adjacent word constraints
if is_valid_order:
return ''.join(candidate_order)
return ""To figure out the secret alphabet order, we can think of each letter as a point on a map and the rules from the given words as one-way streets between them. By looking at how words are ordered, we can map out which letter must come before another and then arrange all the letters in a valid sequence.
Here's how the algorithm would work step-by-step:
def alien_order(word_list):
unique_characters = {char for word in word_list for char in word}
adjacency_list = {char: set() for char in unique_characters}
in_degree_count = {char: 0 for char in unique_characters}
# Comparing adjacent words reveals prerequisite character order constraints.
for current_index in range(len(word_list) - 1):
first_word = word_list[current_index]
second_word = word_list[current_index + 1]
minimum_length = min(len(first_word), len(second_word))
if len(first_word) > len(second_word) and first_word[:minimum_length] == second_word[:minimum_length]:
return ""
for char_index in range(minimum_length):
source_char = first_word[char_index]
target_char = second_word[char_index]
if source_char != target_char:
if target_char not in adjacency_list[source_char]:
adjacency_list[source_char].add(target_char)
in_degree_count[target_char] += 1
break
# Initializing queue with zero incoming edges to start topological traversal.
queue_nodes = [char for char in unique_characters if in_degree_count[char] == 0]
result_list = []
while queue_nodes:
current_char = queue_nodes.pop(0)
result_list.append(current_char)
for neighbor_char in adjacency_list[current_char]:
in_degree_count[neighbor_char] -= 1
if in_degree_count[neighbor_char] == 0:
queue_nodes.append(neighbor_char)
# Verifying all unique characters are ordered ensures absence of circular dependencies.
if len(result_list) != len(unique_characters):
return ""
return "".join(result_list)| Case | How to Handle |
|---|---|
| Empty or null word list | Return an empty string immediately as there are no characters or ordering rules to process. |
| List with a single word | Extract all unique characters from that single word and return them in any or insertion order since no relative ordering can be derived. |
| Invalid prefix ordering where a longer word precedes its own prefix | Detect this violation during comparison and return an empty string because a prefix cannot be lexicographically larger than the full word. |
| Graph contains a cycle | Use Kahn's algorithm or DFS with three state coloring to detect cycles, returning an empty string if a dependency loop prevents topological sorting. |
| Multiple valid character orderings exist | Return any valid topological sort order as the problem accepts any correct character sequence that satisfies all constraints. |
| Disconnected characters not present in any adjacency rules | Initialize all unique characters from the input words in the graph data structure so they are successfully included in the final output string. |
| Large scale inputs with maximum unique characters and words | Ensure the graph construction and topological sort execute in linear time relative to the total number of characters, scaling efficiently. |