Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Hard Topological Sort High frequency Solution Available Practice Mode

Alien Dictionary LeetCode Solution

Tags: #Array #String #Graph #Topological Sort

Approach Summary

Extract precedence rules by comparing adjacent words at the first differing character, build a directed graph (DAG), and run topological sort with cycle detection.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Topological Sort Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Topological Sort pattern.

Framework: Topological Sort • Interview Prep: Tested at FAANG • Explore all Topological Sort problems & invariants →

How to Recognize This Pattern

  • Derive character ordering from sorted foreign language dictionary
  • DAG topological ordering with cycle check

Complexity Analysis

Time Complexity

O(C)

Space Complexity

O(1)

Tags

Array String Graph Topological Sort

Frequently Asked Questions

What is the optimal time and space complexity for Alien Dictionary?
The optimal solution for Alien Dictionary achieves O(C) runtime complexity and requires O(1) auxiliary space. Building the graph takes O(C) time where C is the total length of all words across the dictionary. Topological sort visits each unique character V and edge E once, taking O(V + E). Since the alphabet is bounded (at most 26 lowercase English letters), V ≤ 26 and E ≤ 26², so time is bounded by O(C) and space is O(1) bounded auxiliary space.
How do I identify that Alien Dictionary requires the Topological Sort pattern?
In technical interviews, look for key problem signals: Derive character ordering from sorted foreign language dictionary; DAG topological ordering with cycle check. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Topological Sort strategy.
What critical edge cases must be handled in Alien Dictionary?
Essential edge cases to verify include: Invalid prefix ordering: e.g. ["abc", "ab"] where the second word is a prefix of the first (returns ""); Cycles in precedence: e.g. a -> b and b -> a (returns ""); Single character or single word dictionary; Disconnected graph components (any valid topological order among disjoint sets is accepted). Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Alien Dictionary?
Alien Dictionary is a Hard-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Facebook, Amazon, Google, Airbnb, Pinterest.
Buy me a coffee
Daily Practice
0/0