Skip to main content

Alien Dictionary - Solution & Explanation

HardPremiumFree on FleetCodeArrayStringDepth-First SearchBreadth-First Search7 min readAsked at: Amazon, Microsoft, Apple +15
Practice this problem

Problem Statement

There is a new alien language that uses the English alphabet. However, the order of the letters is unknown to you.

You are given a list of strings words from the alien language's dictionary. Now it is claimed that the strings in words are sorted lexicographically by the rules of this new language.

If this claim is incorrect, and the given arrangement of string in words cannot correspond to any order of letters, return "".

Otherwise, return a string of the unique letters in the new alien language sorted in lexicographically increasing order by the new language's rules. If there are multiple solutions, 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 only lowercase English letters.

Approach Overview

Problem Overview: You’re given a list of words already sorted according to an unknown alien language. Your task is to reconstruct the ordering of characters in that language. If the ordering is invalid (for example, a prefix rule violation), return an empty string.

Approach 1: Graph Construction + Kahn's Algorithm (BFS Topological Sort) (Time: O(V + E), Space: O(V + E))

Model the problem as a directed graph where each character is a node. Compare adjacent words in the sorted list and find the first position where they differ. That difference reveals the ordering rule: char1 -> char2. Build an adjacency list and track indegrees for each character. Then run a Breadth-First Search using Kahn’s algorithm: push all characters with indegree 0 into a queue and process them while decreasing neighbors' indegrees. The result forms the alien character order. If you process fewer nodes than exist, a cycle exists and the ordering is invalid.

This approach is preferred because BFS naturally produces a valid topological ordering while detecting cycles through leftover nodes. It also cleanly handles disconnected components in the graph.

Approach 2: Graph Construction + DFS Topological Sort (Time: O(V + E), Space: O(V + E))

The graph construction step is identical: compare adjacent words and add a directed edge for the first mismatching characters. Instead of using a queue, run a Depth-First Search to produce a topological ordering. Track node states (unvisited, visiting, visited). If DFS reaches a node marked as visiting, a cycle exists and the dictionary is invalid. After exploring all neighbors, push the node into a result stack. Reverse the stack to get the final character order.

This method is common in classic topological sort implementations. It’s slightly more compact but requires careful cycle detection with recursion state tracking.

Key Edge Case: Invalid Prefix

If a longer word appears before its prefix (for example "abc" before "ab"), the ordering is impossible. Detect this while comparing adjacent words. If the first word starts with the second but is longer, return an empty string immediately.

Recommended for interviews: Build the character graph and run BFS with Kahn’s algorithm. Interviewers expect you to recognize the hidden topological sorting problem. Showing how to extract ordering constraints from adjacent words demonstrates strong graph modeling skills, while the BFS solution shows you understand cycle detection and dependency ordering.

Solution

Code

Python

Java

C++

Go

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Graph + BFS (Kahn's Algorithm)O(V + E)O(V + E)Preferred approach for interviews; naturally produces valid topological order and detects cycles
Graph + DFS Topological SortO(V + E)O(V + E)Good when implementing classic DFS-based topo sort with recursion and cycle detection
Naive Pairwise Character OrderingO(N * L)O(V)Useful for understanding how ordering constraints are extracted before building the graph

Video Solution

G-26. Alien Dictionary - Topological Sorttake U forward355,138 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Alien Dictionary easy or hard?
Alien Dictionary is considered a Hard problem because the challenge lies in modeling the graph correctly from word comparisons. After recognizing it as a topological sort problem, the algorithm itself is standard, but handling edge cases like prefix conflicts and cycles makes it tricky.
How to solve Alien Dictionary in O(n)?
Treat the problem as a topological sorting task. Compare adjacent words to build a directed graph of character dependencies, then run BFS (Kahn's algorithm) or DFS to generate the order. The complexity becomes O(V + E), which is linear relative to the number of characters and ordering constraints.
What is the best approach for Alien Dictionary?
The best approach models characters as nodes in a directed graph and extracts ordering constraints by comparing adjacent words. After building the graph, run a topological sort using Kahn’s algorithm (BFS) or DFS. Both run in O(V + E) time where V is the number of characters and E is the number of ordering relations.
What data structure is used in Alien Dictionary?
The main data structures are a graph (adjacency list) to store character dependencies, an indegree map to track prerequisites, and a queue or recursion stack for topological sorting. Hash maps and sets are commonly used to represent the graph efficiently.
What is the time complexity of Alien Dictionary?
The optimal solution runs in O(V + E) time and O(V + E) space. V represents the number of unique characters and E represents precedence rules derived from adjacent words. Graph construction and the topological sort each take linear time relative to nodes and edges.
Alien Dictionary Python or Java solution approach?
Python and Java solutions typically build an adjacency list using a dictionary or HashMap and track indegrees with another map or array. Then Kahn’s BFS algorithm processes nodes with indegree 0 using a queue. The same logic applies across Python, Java, C++, and Go implementations.
Is Alien Dictionary asked at Google, Amazon, or Meta?
Alien Dictionary frequently appears in interviews at companies like Google, Amazon, Meta, and Microsoft. The problem tests graph modeling, dependency resolution, and topological sorting—core concepts used in build systems and scheduling problems.

Ready to solve this problem?

Practice Alien Dictionary with our built-in code editor and test cases.

Practice on FleetCode