0% found this document useful (0 votes)
26 views

Implement Trie (Prefix Tree) - LeetCode

Uploaded by

mystockadvices
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Implement Trie (Prefix Tree) - LeetCode

Uploaded by

mystockadvices
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

New

LeetCode is hiring! Apply NOW. 2


Explore Problems Interview Contest Discuss Store 0

Description Solution Discuss (999+) Submissions Python3 !


Autocomplete
208. Implement Trie (Prefix Tree)
Medium 6835 91 Add to List Share

1▾ class Trie:
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and 2
retrieve keys in a dataset of strings. There are various applications of this data structure, such as 3 def __init__(self):
4
autocomplete and spellchecker. 5
6 def insert(self, word: str)
Implement the Trie class: -> None:
7
Trie() Initializes the trie object. 8
void insert(String word) Inserts the string word into the trie. 9 def search(self, word: str)
boolean search(String word) Returns true if the string word is in the trie (i.e., was -> bool:
10
inserted before), and false otherwise. 11
boolean startsWith(String prefix) Returns true if there is a previously inserted string 12 def startsWith(self,
word that has the prefix prefix , and false otherwise. prefix: str) -> bool:
13
14
15
Example 1: 16 # Your Trie object will be
instantiated and called as
such:
Input 17 # obj = Trie()
["Trie", "insert", "search", "search", "startsWith", "insert", "search"] 18 # obj.insert(word)
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] 19 # param_2 = obj.search(word)
20 # param_3 =
Output
obj.startsWith(prefix)
[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 * 104 calls in total will be made to insert , search , and startsWith .

Accepted 569,534 Submissions 981,681

Seen this question in a real interview before? Yes No

Companies

Related Topics

Similar Questions

Console Contribute

Problems Pick One Prev 208/2247 Next Run Code Submit

You might also like