Alien Dictionary

Solution For Alien Dictionary

Problem description:

There is a new alien language that uses the English alphabet, but the order of the letters is unknown to you. You are given a list of words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of the alphabet from the dictionary.


The given problem can be solved using Topological Sort of Graph. We can consider each character of the word as a vertex. For each pair of words, if the corresponding characters at the same position are different, we can connect an edge from the character of the first word to the character of the second word. We can create a directed graph where each vertex represents a character, and the edge represents the order of the character.

Next, we can perform a Topological Sort of the vertices of the graph to compute the order of the alphabet. Topological Sort is an algorithm that takes a directed acyclic graph (DAG) as input and returns a linear ordering of its vertices. The linear ordering is such that for every directed edge (u, v) from vertex u to vertex v, u comes before v in the ordering.


  1. Create a directed graph for the characters in the input dictionary words.
  2. Perform Topological Sort on the graph to get the order of characters.
  3. Return the order of characters as the alphabet order.


Let’s try to implement the above algorithm in Python:

from collections import defaultdict, deque
class Solution:
def alienOrder(self, words: List[str]) -> str:
# Create directed graph of characters
graph = defaultdict(set)
indegree = defaultdict(int)
for i in range(len(words)-1):
word1, word2 = words[i], words[i+1] for j in range(min(len(word1), len(word2))):
if word1[j] == word2[j]:
if word2[j] not in graph[word1[j]]:
indegree[word2[j]] += 1
if len(word1) > len(word2):
return “”
# Perform Topological Sort
order = [] queue = deque([c for c in indegree if indegree[c] == 0])
while queue:
curr = queue.popleft()
for neighbor in graph[curr]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
if len(order) == len(indegree):
return “”.join(order)
return “”

Time Complexity: O(N), where N is the total number of characters in all words.
Space Complexity: O(26) = O(1), as the input contains only lowercase letters of English alphabet.


Input: words = [“wrt”,”wrf”,”er”,”ett”,”rftt”] Output: “wertf”

Step by Step Implementation For Alien Dictionary

There are multiple ways to solve this problem. One way would be to use a topological sort.

1. Create a graph with the aliens as nodes and the relationships between them as edges.
2. Perform a topological sort on the graph.
3. Output the sorted order of the aliens.
def alienOrder(words):
    # 1. Create a empty graph 
    graph = {}

    # 2. In the case that we have an empty input
    if not words:
        return []

    # 3. Add all the vertices into the graph 
    for word in words:
        for char in word:
            if char not in graph:
                graph[char] = set()

    # 4. Add all the edges into the graph
    # We assume that the first word is always smaller than the second word
    # in the dictionary
    for i in range(len(words) - 1):
        # Find the first different character between the current word and the next word
        j = 0
        while j < len(words[i]) and j < len(words[i + 1]) and words[i][j] == words[i + 1][j]:
            j += 1
        # Add the edge from the current character to the next character
        if j < len(words[i]) and j < len(words[i + 1]):
            graph[words[i][j]].add(words[i + 1][j])

    # 5. Topological sort
    # Initialize the inputs for topological sort
    # visited: default value False, indicates if the node has been visited
    # stack: used to store the order of the characters
    visited = {char: False for char in graph}
    stack = []

    # Call the recursive helper function
    def topological_sort(char):
        # Mark the current node as visited
        visited[char] = True

        # Recurse on all of its neighbors
        for neighbor in graph[char]:
            if not visited[neighbor]:

        # Add the current node to the stack

    # Do the recursive sort
    for char in graph:
        if not visited[char]:

    # 6. Return the order
    return "".join(stack[::-1])
There are multiple ways to solve this problem. One approach would be to use a topological sort.

We can create a graph where each node represents a character and an edge represents a dependency between two characters. In other words, if character A comes before character B in the dictionary, then there will be an edge from A to B in the graph.

We can then use a topological sort to find the order of the characters in the dictionary.

Here is some pseudocode for this approach:

1. Create a graph with characters as nodes and dependencies as edges.
2. Perform a topological sort on the graph.
3. Output the characters in the order determined by the topological sort.
There are multiple ways to solve this problem. One approach would be to use a topological sort.

First, we need to build a graph of the dependencies between the different characters. We can do this by scanning through the words in the dictionary and, for each pair of adjacent words, comparing the characters at each position. If we find a difference, we add an edge from the character at the first word to the character at the second word.

Once we have built the graph, we can perform a topological sort on it to find an ordering of the characters that satisfies the dependencies.

Here is some pseudocode for this approach:

1. Build graph by scanning through dictionary and adding edges for each pair of adjacent words.

2. Perform topological sort on graph.

3. Output the ordering of characters from the topological sort.
public class Solution {
    public string AlienOrder(string[] words) {
        // TODO: Implement your solution here
Scroll to Top

Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]