Alien Dictionary
Problem Statement
You are given a list of words sorted lexicographically according to an unknown alien alphabet. Return any valid ordering of the distinct letters that appear in the words. If the sorted list is inconsistent and no valid alphabet exists, return the empty string.
The only ordering evidence comes from adjacent words: at the first position where two neighbouring words differ, the letter from the first word must come before the letter from the second word. If the earlier word is longer and the later word is its prefix, such as abc before ab, the input is invalid immediately.
Input
An array words that is claimed to be sorted by an unknown alphabet. Only letters that appear in the words should appear in the output.
Output
A string containing one valid ordering of the seen letters, or the empty string if the constraints are contradictory.
Constraints
- •
1 <= words.length <= 100 - •
1 <= words[i].length <= 100 - •
words[i] consists of lowercase English letters - •
All words are sorted according to the alien language if a valid order exists
Examples
Example 1
words = ['wrt','wrf','er','ett','rftt']
wertfExample 2
words = ['z','x']
zxExample 3
words = ['z','x','z']
empty stringExample 4
words = ['abc','ab']
empty stringLearning Objectives
- Derive graph edges from the first differing character in each adjacent word pair.
- Handle the invalid prefix case before topological sorting.
- Topologically sort only the letters that actually appear in the input.
- Avoid duplicate edges so indegrees remain accurate.
Intuition
The words are already sorted, so every adjacent pair is a clue about the alien alphabet. Compare two neighbouring words from left to right. As soon as their characters differ, lexicographic order says the first word's character must be smaller than the second word's character. That single comparison creates one directed edge. Characters after the first difference tell you nothing, because lexicographic order was decided earlier.
The prefix case is the trap. In any lexicographic system, a shorter word must come before its longer extension. Therefore ab can appear before abc, but abc before ab is impossible no matter how letters are ordered. You must reject that before building a misleading graph.
After all edges are collected, the problem becomes Course Schedule II over letters instead of courses. Kahn's algorithm emits letters with no remaining prerequisites. If a cycle remains, the queue dries up too early and the output length is smaller than the number of distinct seen letters.
Common mistakes
- ×Adding edges from every differing character position. Only the first difference matters.
- ×Missing the invalid prefix case where the first word is longer and the second word is its exact prefix.
- ×Including all 26 letters in the result instead of only letters that appear in the input.
- ×Counting duplicate edges multiple times, which inflates indegree and falsely creates a cycle.
- ×Assuming there is a unique answer. Many valid alphabets can satisfy the same constraints.
Algorithm Explanation
- Create graph storage for 26 lowercase letters, plus a seen array. Mark every character that appears and count distinct seen letters.
- For each adjacent pair of words, scan until the first differing index or until one word ends.
- If no difference exists and the first word is longer, return the empty string because the prefix order is invalid.
- If a first difference exists, add an edge firstChar → secondChar. Only increment indegree the first time that edge is added.
- Enqueue every seen letter with indegree 0.
- Run Kahn's algorithm, appending each popped letter to the answer and decrementing its outgoing neighbours.
- Return the answer only if its length equals the number of seen letters; otherwise a cycle made the dictionary invalid.
Solutions
Solution: Kahn's topological sort over seen letters
Extract precedence edges from adjacent word pairs, reject invalid prefixes immediately, then run Kahn's algorithm on the distinct letters that actually appear.
Step-by-step
- Initialise 26 adjacency sets so duplicate edges are naturally ignored.
- Mark all letters seen while scanning all words.
- Compare words[i] and words[i + 1]. The first different characters form an edge; if there is no difference and the first word is longer, return empty.
- Seed the queue with seen letters whose indegree is 0.
- Pop letters into a StringBuilder and relax outgoing edges.
- If the StringBuilder length is smaller than the number of seen letters, a cycle exists, so return empty.
O(C + A)
O(A)
C is the total number of characters scanned; A is bounded by 26 letters and their edges.
Java implementation
Dry Run
Sample input
words = ['wrt','wrf','er','ett','rftt']. Compare adjacent pairs and then run Kahn's algorithm on the seen letters {w,r,t,f,e}.
| Step | Evidence | Edge added | Zero-indegree queue | Order so far |
|---|---|---|---|---|
| Compare 1 | wrt vs wrf first differs at t/f | t → f | - | - |
| Compare 2 | wrf vs er first differs at w/e | w → e | - | - |
| Compare 3 | er vs ett first differs at r/t | r → t | - | - |
| Compare 4 | ett vs rftt first differs at e/r | e → r | [w] | |
| Kahn 1 | pop w | decrement e | [e] | w |
| Kahn 2 | pop e | decrement r | [r] | we |
| Kahn 3 | pop r | decrement t | [t] | wer |
| Kahn 4 | pop t | decrement f | [f] | wert |
| Kahn 5 | pop f | none | [] | wertf |
The output length is 5, which matches the five seen letters, so there is no cycle. The inferred chain w → e → r → t → f yields wertf.
Interview Tips
Lead with the edge-extraction rule, not with topological sort. Interviewers are testing whether you know what evidence a sorted dictionary actually provides. State the prefix invalid case explicitly before coding; it is the most common missed edge case. Use sets for adjacency so duplicate constraints do not corrupt indegrees, and remind the interviewer that any valid character order is acceptable.
Likely follow-ups
- Return the lexicographically smallest valid alien order by using a min-heap for zero-indegree letters.
- Detect whether the alien order is unique or whether multiple answers are possible.
- Support arbitrary Unicode symbols instead of only lowercase English letters.
- Given a proposed alphabet, verify whether the word list is sorted under it.
Similar Problems
Key Takeaways
- Adjacent sorted words reveal one edge from their first differing character only.
- A longer word before its own prefix is impossible and must return empty immediately.
- Topologically sort only characters that appear in the input.
- Duplicate edges must not increment indegree more than once.
- A shorter-than-seen output means a cycle in the inferred alphabet.