mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 13:12:44 +00:00
114 lines
3.4 KiB
Plaintext
114 lines
3.4 KiB
Plaintext
---
|
|
title: '208. Implement Trie (Prefix Tree)'
|
|
description: 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
|
|
icon: dot
|
|
sidebar:
|
|
label: 'Implement Trie (Prefix Tree)'
|
|
badge: 'Medium'
|
|
---
|
|
|
|
<Badge variant="accent">Hash Table</Badge>
|
|
|
|
### Example 1:
|
|
- Input: ``
|
|
- Output: ``
|
|
- Explanation: Input ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] `[[]`, `["apple"]`, `["apple"]`, `["app"]`, `["app"]`, `["app"]`, ["app"]] Output [null, null, true, false, true, null, true] Explanation Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // return True trie.search("app"); // return False trie.startsWith("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 startsWith.
|
|
|
|
## Approach
|
|
|
|
```mermaid
|
|
flowchart TD
|
|
subgraph state["state — root TrieNode; every node holds a children dict and an endOfWord flag"]
|
|
R["root"] --- C["... children[c] ..."] --- L["endOfWord = True — a word ends here"]
|
|
end
|
|
subgraph insert["insert(word)"]
|
|
I1["cur = root"] --> I2{"more c in word?"}
|
|
I2 -- yes --> I3{"c not in cur.children?"}
|
|
I3 -- yes --> I4["cur.children[c] = TrieNode()"]
|
|
I4 --> I5["cur = cur.children[c]"]
|
|
I3 -- no --> I5
|
|
I5 --> I2
|
|
I2 -- no --> I6["cur.endOfWord = True"]
|
|
I6 --> I7(["done"])
|
|
end
|
|
subgraph search["search(word)"]
|
|
S1["cur = root"] --> S2{"more c in word?"}
|
|
S2 -- yes --> S3{"c not in cur.children?"}
|
|
S3 -- yes --> S4(["return False"])
|
|
S3 -- no --> S5["cur = cur.children[c]"]
|
|
S5 --> S2
|
|
S2 -- no --> S6(["return cur.endOfWord — the path exists, but is it a whole word?"])
|
|
end
|
|
subgraph startsWith["startsWith(prefix)"]
|
|
P1["cur = root"] --> P2{"more c in prefix?"}
|
|
P2 -- yes --> P3{"c not in cur.children?"}
|
|
P3 -- yes --> P4(["return False"])
|
|
P3 -- no --> P5["cur = cur.children[c]"]
|
|
P5 --> P2
|
|
P2 -- no --> P6(["return True — every prefix char had a path"])
|
|
end
|
|
state --> insert
|
|
state --> search
|
|
state --> startsWith
|
|
```
|
|
|
|
## Solution
|
|
|
|
```py
|
|
class TrieNode:
|
|
def __init__(self):
|
|
self.children = {}
|
|
self.endOfWord = False
|
|
|
|
|
|
class Trie:
|
|
def __init__(self):
|
|
self.root = TrieNode()
|
|
|
|
def insert(self, word: str) -> None:
|
|
cur = self.root
|
|
|
|
for c in word:
|
|
if c not in cur.children:
|
|
cur.children[c] = TrieNode()
|
|
cur = cur.children[c]
|
|
cur.endOfWord = True
|
|
|
|
def search(self, word: str) -> bool:
|
|
cur = self.root
|
|
|
|
for c in word:
|
|
if c not in cur.children:
|
|
return False
|
|
cur = cur.children[c]
|
|
|
|
return cur.endOfWord
|
|
|
|
def startsWith(self, prefix: str) -> bool:
|
|
cur = self.root
|
|
|
|
for c in prefix:
|
|
if c not in cur.children:
|
|
return False
|
|
cur = cur.children[c]
|
|
|
|
return True
|
|
|
|
|
|
# Your Trie object will be instantiated and called as such:
|
|
# obj = Trie()
|
|
# obj.insert(word)
|
|
# param_2 = obj.search(word)
|
|
# param_3 = obj.startsWith(prefix)
|
|
```
|
|
|
|
## Explanation
|
|
|
|
<YouTube id="oobqoCJlHA0" title="Implement Trie (Prefix Tree) - Leetcode 208" />
|