> ## 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.

# Implement Trie (Prefix Tree) Python Solution

> Tested Python solution for LeetCode 208 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 208, Medium. Topics: Hash Table, String, Design, Trie. [View on LeetCode](https://leetcode.com/problems/implement-trie-prefix-tree/description/).

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

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

## Problem

A **trie** (pronounced as "try") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

* `Trie()` Initializes the trie object.
* `void insert(String word)` Inserts the string `word` into the trie.
* `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
* `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.

### Examples

```
Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]
```

**Explanation:**

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
trie = Trie()
trie.insert("apple")
trie.search("apple")    # return True
trie.search("app")      # return False
trie.starts_with("app") # return True
trie.insert("app")
trie.search("app")      # return True
```

### Constraints

* `1 <= word.length, prefix.length <= 2000`
* `word` and `prefix` consist only of lowercase English letters.
* At most `3 * 10^4` calls **in total** will be made to `insert`, `search`, and `starts_with`.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py.data_structures import DictTree, RecursiveDict


class Trie(DictTree[str]):
    END_OF_WORD = "#"

    # Time: O(1)
    # Space: O(1)
    def __init__(self) -> None:
        self.root: RecursiveDict[str] = {}

    # Time: O(m) where m is word length
    # Space: O(m)
    def insert(self, word: str) -> None:
        node = self.root
        for char in word:
            if char not in node:
                node[char] = {}
            node = node[char]
        node[self.END_OF_WORD] = True

    # Time: O(m) where m is word length
    # Space: O(1)
    def search(self, word: str) -> bool:
        node = self.root
        for char in word:
            if char not in node:
                return False
            node = node[char]
        return self.END_OF_WORD in node

    # Time: O(m) where m is prefix length
    # Space: O(1)
    def starts_with(self, prefix: str) -> bool:
        node = self.root
        for char in prefix:
            if char not in node:
                return False
            node = node[char]
        return True
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(1) | O(1)  |

## Tags

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