medium +30 pts

Alien Dictionary Order

Decode the alien alphabet by analyzing word ordering constraints.

In an alien language, the letters are ordered by some unknown sequence. You are given a list of words from the alien dictionary, sorted lexicographically according to the alien alphabet. Your task is to deduce the order of letters in the alien alphabet. Write a function `alien_order(words: list[str]) -> str` that returns the alien alphabet order as a string consisting of all unique letters that appear in the words, in the deduced order. If the order cannot be determined uniquely, return any valid order. If the given words are inconsistent (impossible to deduce any order), return an empty string `""`. The words are sorted lexicographically according to the alien alphabet. This means that for any two consecutive words `a` and `b`, either `a` is a prefix of `b`, or at the first differing position, the letter in `a` comes before the letter in `b`. Inconsistency examples: - If a word is a prefix of another word but appears after it (e.g., `["abc", "ab"]`), the order is invalid. - If the constraints create a cycle (e.g., `["x", "z", "x"]` implies `x < z` and `z < x`), the order is invalid. Input Constraints: - `1 <= len(words) <= 100` - `1 <= len(words[i]) <= 20` - The words consist only of lowercase English letters. - All letters that appear in the words are unique in the answer. Return the order as a string of characters with no separators. If multiple valid orders exist, any one of them is acceptable.

Constraints

Number of words: 1–100. Word length: 1–20. Only lowercase letters. The output must contain each appearing letter exactly once. Complexity: O(total number of letters in the words + number of edges).

Example

```python
>>> alien_order(["wrt","wrf","er","ett","rftt"])
"wertf"

>>> alien_order(["z","x"])
"zx"

>>> alien_order(["z","x","z"])
""

>>> alien_order(["ab","adc"])
"abcd"  # or any valid order like "acbd"
```
30 points ~30 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Compare each pair of consecutive words to extract a directed edge (letter before another).
Use a graph and perform a topological sort (Kahn's algorithm) to produce the order.
If the number of letters in the output does not match the total unique letters, the order is inconsistent.
Beware of the prefix rule: if a word is a prefix of the next word but appears after it, return empty string.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.