Skip to content

Commit 705a2f6

Browse files
committed
LeetCode Trie Prefix Tree
1 parent 8d61103 commit 705a2f6

File tree

3 files changed

+116
-3
lines changed

3 files changed

+116
-3
lines changed

README.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ A comprehensive collection of coding challenges from multiple platforms for lear
66

77
| Platform | Focus Area | Problems Solved |
88
| -------------------------------- | ---------------------------- | --------------- |
9-
| [LeetCode](#-leetcode) | Data Structures & Algorithms | 161 |
9+
| [LeetCode](#-leetcode) | Data Structures & Algorithms | 162 |
1010
| [GreatFrontEnd](#-greatfrontend) | Frontend Engineering | 5 |
1111

1212
## 🎯 Platforms
@@ -18,7 +18,7 @@ A comprehensive collection of coding challenges from multiple platforms for lear
1818
**Progress**:
1919

2020
- Easy: 80 problems
21-
- Medium: 69 problems
21+
- Medium: 70 problems
2222
- Hard: 12 problems
2323

2424
**Quick Links**:
@@ -180,11 +180,12 @@ A comprehensive collection of coding challenges from multiple platforms for lear
180180
</details>
181181

182182
<details>
183-
<summary>🟡 Medium Problems (69 solved)</summary>
183+
<summary>🟡 Medium Problems (70 solved)</summary>
184184

185185
### Stack & Design
186186

187187
- [0155 - Min Stack](./leetcode/medium/0155-min-stack) ![Medium](https://img.shields.io/badge/Medium-orange)
188+
- [0208 - Implement Trie (Prefix Tree)](./leetcode/medium/0208-implement-trie-prefix-tree) ![Medium](https://img.shields.io/badge/Medium-orange)
188189

189190
### Array & Two Pointers
190191

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree) ![Medium](https://img.shields.io/badge/Medium-orange)
2+
3+
A [**trie**](https://en.wikipedia.org/wiki/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.
4+
5+
Implement the Trie class:
6+
7+
- `Trie()` Initializes the trie object.
8+
- `void insert(String word)` Inserts the string `word` into the trie.
9+
- `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
10+
- `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
11+
12+
## Example 1
13+
14+
```bash
15+
Input
16+
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
17+
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
18+
19+
Output
20+
[null, null, true, false, true, null, true]
21+
22+
Explanation
23+
Trie trie = new Trie();
24+
trie.insert("apple");
25+
trie.search("apple"); // return True
26+
trie.search("app"); // return False
27+
trie.startsWith("app"); // return True
28+
trie.insert("app");
29+
trie.search("app"); // return True
30+
```
31+
32+
## Constraints
33+
34+
- `1 <= word.length, prefix.length <= 2000`
35+
- `word` and `prefix` consist only of lowercase English letters.
36+
- At most `3 * 10^4` calls **in total** will be made to `insert`, `search`, and `startsWith`.
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
class TrieNode {
2+
children: { [key: string]: TrieNode } = {};
3+
isEndOfWord: boolean = false;
4+
}
5+
6+
/*
7+
* @time - All operations run in O(L) time where L is the word length. This is because we process each character once.
8+
* @space - Depends on the total number of characters across all words inserted, but shared prefixes help to reduce redundancy.
9+
*/
10+
class Trie {
11+
private root: TrieNode;
12+
13+
constructor() {
14+
this.root = new TrieNode();
15+
}
16+
17+
// @time - O(L) where L is the length of the word
18+
insert(word: string): void {
19+
// Start at root
20+
let current = this.root;
21+
// For each char in word...
22+
for (const char of word) {
23+
// If char not in current.children, add new TrieNode
24+
// Each lookup/insertion is O(1)
25+
if (!current.children[char]) {
26+
current.children[char] = new TrieNode();
27+
}
28+
// Move to the child node for this character
29+
current = current.children[char];
30+
}
31+
// Mark the last node as end of a word
32+
current.isEndOfWord = true;
33+
}
34+
35+
// @time - O(L) where L is the length of the word
36+
search(word: string): boolean {
37+
let current = this.root;
38+
// Traverse word
39+
for (const char of word) {
40+
// If char not found in current.children then the word does not exists
41+
// Each child being accessed is O(1)
42+
if (!current.children[char]) {
43+
return false;
44+
}
45+
// Move to the child node
46+
current = current.children[char];
47+
}
48+
// After traversing, check if current is end of the word
49+
return current.isEndOfWord;
50+
}
51+
52+
// @time - O(L) where L is the length of the prefix
53+
startsWith(prefix: string): boolean {
54+
// Same as search, but return true if path exists (ignore isEndOfWord)
55+
let current = this.root;
56+
57+
for (const char of prefix) {
58+
// Each child being accessed is O(1)
59+
if (!current.children[char]) {
60+
return false;
61+
}
62+
current = current.children[char];
63+
}
64+
65+
// Full prefix path exits
66+
return true;
67+
}
68+
}
69+
70+
/**
71+
* Your Trie object will be instantiated and called as such:
72+
* var obj = new Trie()
73+
* obj.insert(word)
74+
* var param_2 = obj.search(word)
75+
* var param_3 = obj.startsWith(prefix)
76+
*/

0 commit comments

Comments
 (0)