Taro Logo

Alien Dictionary

#1 Most AskedHard
Topics:
GraphsArraysTopological Sort

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 <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists of lowercase English letters.

Solution


Clarifying Questions

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:

  1. What should we return if the input word list is empty or contains only a single word?
  2. How should we handle invalid orderings where a longer word appears before its own prefix (e.g., ["abc", "ab"])?
  3. If there are multiple valid character orderings that satisfy the alien dictionary rules, should we return any valid order, or is there a specific tie-breaking rule (like lexicographical order)?
  4. Are all characters in the words guaranteed to be lowercase English letters, or could they include uppercase letters, numbers, or special symbols?
  5. What should be returned if characters appear in the word list that never establish a relative ordering with other characters?

Brute Force Solution

Approach

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:

  1. Gather all the unique letters present in the given list of words.
  2. Generate every possible arrangement of these letters, starting with all the different ways they could be sequenced from first to last.
  3. Pick the first guessed alphabet order from your list of possibilities.
  4. Compare the given words side by side to see if they appear in the correct sorted sequence according to your currently guessed alphabet.
  5. Check if every adjacent pair of words strictly obeys the rule that the earlier word should come before the later word based on your guess.
  6. If the words do not match your guessed alphabet order, throw away that guess and move on to the next possible alphabet arrangement.
  7. Keep trying different alphabet arrangements until you find one that successfully satisfies the ordering of all the given words.

Code Implementation

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 ""

Big(O) Analysis

Time Complexity
O(V! * W * L) – Let V be the number of unique letters, W be the number of words, and L be the maximum length of a word. Generating every possible arrangement of the V unique letters results in V! permutations. For each generated alphabet order, we must compare adjacent words side by side across the entire list, taking W times L operations to validate the sequence. This leads to approximately V! * W * L operations, which simplifies to the factorial and polynomial time complexity of O(V! * W * L).
Space Complexity
O(1) – To analyze the auxiliary space of the brute force approach, we must look at the data structures required to generate and test every possible alphabet arrangement. The process relies on a unique set of letters gathered from the words and a permutation generator to cycle through alphabet orders. Because the alien alphabet is constrained by a fixed maximum size of 26 English letters, the number of unique letters and possible permutations has an upper bound independent of the input size. Therefore, the memory used by the unique character set, the generated permutations, and the comparison variables remains constant, resulting in an O(1) auxiliary space complexity.

Optimal Solution

Approach

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:

  1. Collect all the unique letters used in the given words so we know every character we need to place in our final alphabet.
  2. Compare adjacent words in the list to find the very first spot where their letters differ.
  3. Create a directed relationship from the differing letter in the earlier word to the differing letter in the later word, establishing that the first must come before the second.
  4. Examine the entire network of these relationships to ensure there are no contradictory loops, such as a letter needing to come both before and after another letter.
  5. Order the letters by starting with any character that has no other letters required to come before it.
  6. Remove each successfully ordered letter and its associated relationships from the map, then repeat the process until all letters have been placed in their correct sequence.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(V + E) – The time complexity is driven by finding unique characters across all words, which takes time proportional to the total number of characters, plus processing the adjacency list of unique letters (V) and their directed rules (E). Comparing adjacent words to build these rules takes time proportional to the sum of the lengths of all words in the input. Finally, topological sorting visits every unique character and relationship once to order the alphabet without contradictory loops. This results in operations roughly bounded by the sum of all characters and rules, simplifying to O(V + E).
Space Complexity
O(1) – To determine the auxiliary space complexity, let V be the total number of unique characters in the alien alphabet and E be the total number of adjacency rules derived from comparing adjacent words. The hash map representing the adjacency list stores at most V keys with up to V total directed edges, while the visited tracking set and output list each scale directly with V. Since the alphabet size is bounded by a constant number of lowercase English letters (at most 26), these data structures require a fixed amount of extra memory regardless of the input word list size. Therefore, the auxiliary space complexity simplifies to O(1) in terms of Big O notation.

Edge Cases

Empty or null word list
How to Handle:
Return an empty string immediately as there are no characters or ordering rules to process.
List with a single word
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Ensure the graph construction and topological sort execute in linear time relative to the total number of characters, scaling efficiently.
0/15 completed