Reconstruct Alphabet Order from Sorted Vocabulary
Trees & GraphsAuto-graded · 25 test casesLast updated
Determine character precedence in an unfamiliar alphabet using a sorted list of terms, returning the lexicographically first valid character sequence or an empty string for invalid inputs.
Given a sequence of strings words sorted according to the rules of an unfamiliar alphabet, reconstruct the relative ordering of all characters present in the vocabulary.
If the input is logically inconsistent (for example, a string appears before a shorter prefix of itself, or there are circular ordering dependencies), return an empty string "".
If multiple valid character orderings exist, return the one that is alphabetically smallest when comparing the character sequences themselves using standard English alphabetical order.
Constraints
1 <= len(words) <= 1001 <= len(words[i]) <= 100words[i]contains only lowercase English letters.
Examples
Example 1
Input: find_alien_order(['wrt', 'wrf', 'er', 'ett', 'rftt'])
Output: 'wertf'
Example 2
Input: find_alien_order(['z', 'x', 'z'])
Output: ''
Example 3
Input: find_alien_order(['z', 'x'])
Output: 'zx'
Hints
Hint 1
Adjacent words in the sorted array provide the immediate ordering relationships between characters.
Hint 2
Watch out for edge cases where a longer word appears before its own prefix—this is invalid in standard lexicographical ordering.
Hint 3
Use Kahn's algorithm paired with a priority queue (min-heap) to build the ordering while breaking ties lexicographically.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task requires establishing a linear order among characters based on pairwise lexicographical relationships derived from a sorted list of words.
-
Extract Directed Dependencies:
- Compare each consecutive pair of words
(words[i], words[i+1]). - Find the first index where characters differ:
words[i][k] != words[i+1][k]. This difference indicates thatwords[i][k]must precedewords[i+1][k]in the custom alphabet. Add a directed edgewords[i][k] -> words[i+1][k]to our dependency graph and break (subsequent character differences in the same word pair do not provide direct precedence info). - Prefix Check: If no mismatch is found before reaching the end of one word, ensure the shorter word came first. If a longer word precedes its prefix (e.g.,
"abc"followed by"ab"), the list is invalid, so return"".
- Compare each consecutive pair of words
-
Topological Ordering with Tie-Breaking:
- Track the in-degree of every unique character appearing across all words.
- Use Kahn's algorithm with a min-heap to perform topological sorting. At each step, extract the lexicographically smallest character currently having an in-degree of 0.
- Reduce the in-degrees of its outgoing neighbors and push any newly freed characters into the heap.
-
Cycle Detection:
- If the final output sequence length matches the count of unique characters in the input, a valid sequence has been constructed. Otherwise, a circular dependency exists, making an ordering impossible (return
"").
- If the final output sequence length matches the count of unique characters in the input, a valid sequence has been constructed. Otherwise, a circular dependency exists, making an ordering impossible (return
Complexity Analysis
- Time Complexity: $O(C + U \log U)$ where $C$ is the total number of characters across all input words and $U$ is the total count of unique characters. Comparing adjacent words takes $O(C)$ operations in total. The topological sort processes $U$ nodes and up to $U^2$ edges using a min-heap. Since $U \le 26$ for lowercase English letters, this simplifies to $O(C)$.
- Space Complexity: $O(U + E)$ where $E$ is the number of precedence edges. Given $U \le 26$, this uses $O(1)$ extra space beyond storing the input.
import heapq
from typing import List
def find_alien_order(words: List[str]) -> str:
# Identify all distinct characters in the input
chars = set("".join(words))
graph = {char: set() for char in chars}
indegree = {char: 0 for char in chars}
# Build dependency graph from adjacent pairs
for first, second in zip(words, words[1:]):
limit = min(len(first), len(second))
for i in range(limit):
if first[i] != second[i]:
u, v = first[i], second[i]
if v not in graph[u]:
graph[u].add(v)
indegree[v] += 1
break
else:
# Check for invalid prefix ordering
if len(first) > len(second):
return ""
# Kahn's algorithm with min-heap
ready = [char for char in chars if indegree[char] == 0]
heapq.heapify(ready)
order = []
while ready:
char = heapq.heappop(ready)
order.append(char)
for neighbor in graph[char]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
heapq.heappush(ready, neighbor)
return "".join(order) if len(order) == len(chars) else ""