> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Alien Dictionary Python Solution with Tests

> Tested Python solution for LeetCode 269 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 269, Hard. Topics: Array, String, Depth-First Search, Breadth-First Search, Graph, Topological Sort. [View on LeetCode](https://leetcode.com/problems/alien-dictionary/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 269   # by problem number
lcpy gen -s alien_dictionary   # by problem name
```

## Problem

There is a new alien language that uses the English alphabet. However, the order among the letters is unknown to you.

You are given a list of strings `words` from the alien language's dictionary, where the strings in `words` are **sorted lexicographically** by the rules of this new language.

Return *a string of the unique letters in the new alien language sorted in **lexicographically increasing order** by the new language's rules. If there is no solution, return* `""`*. If there are multiple solutions, return **any of them***.

### Examples

```
Input: words = ["wrt","wrf","er","ett","rftt"]
Output: "wertf"
```

```
Input: words = ["z","x"]
Output: "zx"
```

```
Input: words = ["z","x","z"]
Output: ""
Explanation: The order is invalid, so return "".
```

### Constraints

* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of only lowercase English letters.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/alien_dictionary/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/alien_dictionary/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(C) where C is total number of characters in all words
    # Space: O(1) since at most 26 characters in alphabet
    def alien_order(self, words: list[str]) -> str:
        # Build adjacency list and in-degree count
        adj: dict[str, set[str]] = {c: set() for word in words for c in word}
        in_degree = dict.fromkeys(adj, 0)

        # Build graph by comparing adjacent words
        for i in range(len(words) - 1):
            w1, w2 = words[i], words[i + 1]
            min_len = min(len(w1), len(w2))

            # Check for invalid case: longer word is prefix of shorter word
            if len(w1) > len(w2) and w1[:min_len] == w2[:min_len]:
                return ""

            # Find first different character and add edge
            for j in range(min_len):
                if w1[j] != w2[j]:
                    if w2[j] not in adj[w1[j]]:
                        adj[w1[j]].add(w2[j])
                        in_degree[w2[j]] += 1
                    break

        # Topological sort using Kahn's algorithm
        queue = [c for c in in_degree if in_degree[c] == 0]
        result = []

        while queue:
            c = queue.pop(0)
            result.append(c)

            for neighbor in adj[c]:
                in_degree[neighbor] -= 1
                if in_degree[neighbor] == 0:
                    queue.append(neighbor)

        # Check for cycle (invalid ordering)
        return "".join(result) if len(result) == len(in_degree) else ""
```

## Complexity

| Time                                                    | Space                                        |
| ------------------------------------------------------- | -------------------------------------------- |
| O(C) where C is total number of characters in all words | O(1) since at most 26 characters in alphabet |

## Tags

[Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
