208. Implement Trie (Prefix Tree)
LeetCode 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.
Implement the Trie class:
Trie()
Initializes the trie object.void insert(String word)
Inserts the stringword
into the trie.boolean search(String word)
Returnstrue
if the stringword
is in the trie (i.e., was inserted before), andfalse
otherwise.boolean startsWith(String prefix)
Returnstrue
if there is a previously inserted stringword
that has the prefixprefix
, andfalse
otherwise.
Example 1:
Constraints:
1 <= word.length, prefix.length <= 2000
word
andprefix
consist only of lowercase English letters.At most
3 * 10^4
calls in total will be made toinsert
,search
, andstartsWith
.
Tags
Design, Trie
Solution
Properties
children [26]*Trie
: an array of pointers to children Trie nodes;isEnd bool: a flag indicates if this node is the last character of a stored string.
Insert
We assign a pointer to the root to search. For each character of the input word, if this character exists in the children array of the current node, we move the pointer to that child; otherwise we create a child node. At last, we set the pointer's isEnd = true
.
Search Prefix
This method returns the last node if the prefix exists. If the character does not exist, return nil.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?