
Problem
Solution
Submissions
Alien Dictionary Problem
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 15
You are given a sorted dictionary of an alien language that has its own order of characters. The dictionary consists of a list of words sorted lexicographically by the rules of this alien language. Derive the order of characters in this alien language.
You have to assume all letters are in lowercase and there are no duplicates in the alien dictionary.
Example 1
- Input: words = ["wrt", "wrf", "er", "ett", "rftt"]
- Output: "wertf"
- Explanation:
- Step 1: Compare adjacent words to find character relationships.
- Step 2: From "wrt" and "wrf", we know 't' comes before 'f'.
- Step 3: From "wrt" and "er", we know 'w' comes before 'e'.
- Step 4: From "er" and "ett", we know 'r' comes before 't'.
- Step 5: From "ett" and "rftt", we know 'e' comes before 'r'.
- Step 6: These relationships form a directed graph: w->e->r->t->f.
- Step 7: Performing a topological sort gives us "wertf".
Example 2
- Input: words = ["z", "x"]
- Output: "zx"
- Explanation:
- Step 1: Compare adjacent words to find character relationships.
- Step 2: From "z" and "x", we know 'z' comes before 'x'.
- Step 3: These relationships form a directed graph: z->x.
- Step 4: Performing a topological sort gives us "zx".
Constraints
- 1 ≤ words.length ≤ 100
- 1 ≤ words[i].length ≤ 100
- words[i] consists of only lowercase English letters.
- The input is guaranteed to produce a valid order of characters (no cycles).
- Time Complexity: O(total number of characters in all words)
- Space Complexity: O(1) or O(unique characters) since there are at most 26 unique characters
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Model this problem as a graph where characters are vertices and their ordering constraints are edges.
- Compare adjacent words to derive the character ordering.
- Use topological sorting to find the order of characters.
- Check for inconsistencies in the input that would make the alien dictionary invalid.
- Handle edge cases like words that are prefixes of other words.