Leetcode #269: Alien Dictionary
In this guide, we solve Leetcode #269 Alien Dictionary in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
There is a new alien language that uses the English alphabet. However, the order of the letters is unknown to you.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Depth-First Search, Breadth-First Search, Graph, Topological Sort, Array, String
Intuition
The data forms a graph, so we should explore nodes and edges systematically.
A traversal ensures we visit each node once while maintaining the needed state.
Approach
Build an adjacency list and traverse with BFS or DFS.
Aggregate results as you visit nodes.
Steps:
- Build the graph.
- Traverse with BFS/DFS.
- Accumulate the required output.
Example
Input: words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
Python Solution
class Solution:
def alienOrder(self, words: List[str]) -> str:
g = [[False] * 26 for _ in range(26)]
s = [False] * 26
cnt = 0
n = len(words)
for i in range(n - 1):
for c in words[i]:
if cnt == 26:
break
o = ord(c) - ord('a')
if not s[o]:
cnt += 1
s[o] = True
m = len(words[i])
for j in range(m):
if j >= len(words[i + 1]):
return ''
c1, c2 = words[i][j], words[i + 1][j]
if c1 == c2:
continue
o1, o2 = ord(c1) - ord('a'), ord(c2) - ord('a')
if g[o2][o1]:
return ''
g[o1][o2] = True
break
for c in words[n - 1]:
if cnt == 26:
break
o = ord(c) - ord('a')
if not s[o]:
cnt += 1
s[o] = True
indegree = [0] * 26
for i in range(26):
for j in range(26):
if i != j and s[i] and s[j] and g[i][j]:
indegree[j] += 1
q = deque()
ans = []
for i in range(26):
if s[i] and indegree[i] == 0:
q.append(i)
while q:
t = q.popleft()
ans.append(chr(t + ord('a')))
for i in range(26):
if s[i] and i != t and g[t][i]:
indegree[i] -= 1
if indegree[i] == 0:
q.append(i)
return '' if len(ans) < cnt else ''.join(ans)
Complexity
The time complexity is O(V+E). The space complexity is O(V).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.