Skip to content

Commit 99a25d4

Browse files
authored
Merge pull request #22 from iamAntimPal/Leetcode-75
Leetcode 75
2 parents f990758 + d1ee741 commit 99a25d4

File tree

2 files changed

+262
-0
lines changed

2 files changed

+262
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Trie:
2+
def __init__(self):
3+
self.children = [None] * 26
4+
self.is_end = False
5+
6+
def insert(self, word: str) -> None:
7+
node = self
8+
for c in word:
9+
idx = ord(c) - ord('a')
10+
if node.children[idx] is None:
11+
node.children[idx] = Trie()
12+
node = node.children[idx]
13+
node.is_end = True
14+
15+
def search(self, word: str) -> bool:
16+
node = self._search_prefix(word)
17+
return node is not None and node.is_end
18+
19+
def startsWith(self, prefix: str) -> bool:
20+
node = self._search_prefix(prefix)
21+
return node is not None
22+
23+
def _search_prefix(self, prefix: str):
24+
node = self
25+
for c in prefix:
26+
idx = ord(c) - ord('a')
27+
if node.children[idx] is None:
28+
return None
29+
node = node.children[idx]
30+
return node
31+
32+
33+
# Your Trie object will be instantiated and called as such:
34+
# obj = Trie()
35+
# obj.insert(word)
36+
# param_2 = obj.search(word)
37+
# param_3 = obj.startsWith(prefix)
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
---
2+
comments: true
3+
difficulty: Medium
4+
edit_url: Antim
5+
tags:
6+
- Design
7+
- Trie
8+
- Hash Table
9+
- String
10+
---
11+
12+
<!-- problem:start -->
13+
14+
# [208. Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree)
15+
16+
17+
## Description
18+
19+
<!-- description:start -->
20+
21+
<p>A <a href="https://en.wikipedia.org/wiki/Trie" target="_blank"><strong>trie</strong></a> (pronounced as &quot;try&quot;) or <strong>prefix tree</strong> 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.</p>
22+
23+
<p>Implement the Trie class:</p>
24+
25+
<ul>
26+
<li><code>Trie()</code> Initializes the trie object.</li>
27+
<li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li>
28+
<li><code>boolean search(String word)</code> Returns <code>true</code> if the string <code>word</code> is in the trie (i.e., was inserted before), and <code>false</code> otherwise.</li>
29+
<li><code>boolean startsWith(String prefix)</code> Returns <code>true</code> if there is a previously inserted string <code>word</code> that has the prefix <code>prefix</code>, and <code>false</code> otherwise.</li>
30+
</ul>
31+
32+
<p>&nbsp;</p>
33+
<p><strong class="example">Example 1:</strong></p>
34+
35+
<pre>
36+
<strong>Input</strong>
37+
[&quot;Trie&quot;, &quot;insert&quot;, &quot;search&quot;, &quot;search&quot;, &quot;startsWith&quot;, &quot;insert&quot;, &quot;search&quot;]
38+
[[], [&quot;apple&quot;], [&quot;apple&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;]]
39+
<strong>Output</strong>
40+
[null, null, true, false, true, null, true]
41+
42+
<strong>Explanation</strong>
43+
Trie trie = new Trie();
44+
trie.insert(&quot;apple&quot;);
45+
trie.search(&quot;apple&quot;); // return True
46+
trie.search(&quot;app&quot;); // return False
47+
trie.startsWith(&quot;app&quot;); // return True
48+
trie.insert(&quot;app&quot;);
49+
trie.search(&quot;app&quot;); // return True
50+
</pre>
51+
52+
<p>&nbsp;</p>
53+
<p><strong>Constraints:</strong></p>
54+
55+
<ul>
56+
<li><code>1 &lt;= word.length, prefix.length &lt;= 2000</code></li>
57+
<li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li>
58+
<li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li>
59+
</ul>
60+
61+
<!-- description:end -->
62+
63+
## Solutions
64+
65+
<!-- solution:start -->
66+
67+
### Solution 1
68+
69+
<!-- tabs:start -->
70+
71+
#### Python3
72+
73+
```python
74+
class Trie:
75+
def __init__(self):
76+
self.children = [None] * 26
77+
self.is_end = False
78+
79+
def insert(self, word: str) -> None:
80+
node = self
81+
for c in word:
82+
idx = ord(c) - ord('a')
83+
if node.children[idx] is None:
84+
node.children[idx] = Trie()
85+
node = node.children[idx]
86+
node.is_end = True
87+
88+
def search(self, word: str) -> bool:
89+
node = self._search_prefix(word)
90+
return node is not None and node.is_end
91+
92+
def startsWith(self, prefix: str) -> bool:
93+
node = self._search_prefix(prefix)
94+
return node is not None
95+
96+
def _search_prefix(self, prefix: str):
97+
node = self
98+
for c in prefix:
99+
idx = ord(c) - ord('a')
100+
if node.children[idx] is None:
101+
return None
102+
node = node.children[idx]
103+
return node
104+
105+
106+
# Your Trie object will be instantiated and called as such:
107+
# obj = Trie()
108+
# obj.insert(word)
109+
# param_2 = obj.search(word)
110+
# param_3 = obj.startsWith(prefix)
111+
```
112+
113+
#### Java
114+
115+
```java
116+
class Trie {
117+
private Trie[] children;
118+
private boolean isEnd;
119+
120+
public Trie() {
121+
children = new Trie[26];
122+
}
123+
124+
public void insert(String word) {
125+
Trie node = this;
126+
for (char c : word.toCharArray()) {
127+
int idx = c - 'a';
128+
if (node.children[idx] == null) {
129+
node.children[idx] = new Trie();
130+
}
131+
node = node.children[idx];
132+
}
133+
node.isEnd = true;
134+
}
135+
136+
public boolean search(String word) {
137+
Trie node = searchPrefix(word);
138+
return node != null && node.isEnd;
139+
}
140+
141+
public boolean startsWith(String prefix) {
142+
Trie node = searchPrefix(prefix);
143+
return node != null;
144+
}
145+
146+
private Trie searchPrefix(String s) {
147+
Trie node = this;
148+
for (char c : s.toCharArray()) {
149+
int idx = c - 'a';
150+
if (node.children[idx] == null) {
151+
return null;
152+
}
153+
node = node.children[idx];
154+
}
155+
return node;
156+
}
157+
}
158+
159+
/**
160+
* Your Trie object will be instantiated and called as such:
161+
* Trie obj = new Trie();
162+
* obj.insert(word);
163+
* boolean param_2 = obj.search(word);
164+
* boolean param_3 = obj.startsWith(prefix);
165+
*/
166+
```
167+
168+
#### C++
169+
170+
```cpp
171+
class Trie {
172+
private:
173+
vector<Trie*> children;
174+
bool isEnd;
175+
176+
Trie* searchPrefix(string s) {
177+
Trie* node = this;
178+
for (char c : s) {
179+
int idx = c - 'a';
180+
if (!node->children[idx]) return nullptr;
181+
node = node->children[idx];
182+
}
183+
return node;
184+
}
185+
186+
public:
187+
Trie()
188+
: children(26)
189+
, isEnd(false) {}
190+
191+
void insert(string word) {
192+
Trie* node = this;
193+
for (char c : word) {
194+
int idx = c - 'a';
195+
if (!node->children[idx]) node->children[idx] = new Trie();
196+
node = node->children[idx];
197+
}
198+
node->isEnd = true;
199+
}
200+
201+
bool search(string word) {
202+
Trie* node = searchPrefix(word);
203+
return node != nullptr && node->isEnd;
204+
}
205+
206+
bool startsWith(string prefix) {
207+
Trie* node = searchPrefix(prefix);
208+
return node != nullptr;
209+
}
210+
};
211+
212+
/**
213+
* Your Trie object will be instantiated and called as such:
214+
* Trie* obj = new Trie();
215+
* obj->insert(word);
216+
* bool param_2 = obj->search(word);
217+
* bool param_3 = obj->startsWith(prefix);
218+
*/
219+
```
220+
221+
<!-- tabs:end -->
222+
223+
<!-- solution:end -->
224+
225+
<!-- problem:end -->

0 commit comments

Comments
 (0)