Implement Trie (Prefix Tree)
A trie (pronounced "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 stringwordinto the trie.boolean search(String word)— Returnstrueif the stringwordis in the trie (i.e., was inserted before), andfalseotherwise.boolean startsWith(String prefix)— Returnstrueif there is a previously inserted stringwordthat has the prefixprefix, andfalseotherwise.
Example 1:
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"); // Inserts "apple" into the trie
trie.search("apple"); // Returns true
trie.search("app"); // Returns false ("app" was not inserted)
trie.startsWith("app"); // Returns true ("apple" starts with "app")
trie.insert("app"); // Inserts "app" into the trie
trie.search("app"); // Returns true ("app" is now in the trie)
Examples
Example 1
Input: ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output: [null, null, true, false, true, null, true]
Explanation: After inserting "apple", searching for "apple" returns true but "app" returns false since it wasn't inserted. startsWith("app") returns true because "apple" has prefix "app". After inserting "app", searching for "app" returns 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
Optimal Complexity
Time
O(m) per operation, where m is the word/prefix length
Space
O(n * m) total, where n is the number of words inserted
Practice this problem with an AI interviewer
TechInView conducts a full voice mock interview — the AI asks clarifying questions, evaluates your approach, watches you code, and scores you on 5 dimensions. Just like a real FAANG interview.
Start a free interview