Medium

Quiz

#208 Implement Trie (Prefix Tree)

APPROACH

A prefix tree (trie, pronounced "try") enables efficient string storage and lookup, powering features like autocomplete and spell-check.

Build the Trie class:

- Trie() sets up an empty trie.

- void insert(String word) stores word in the trie.

- boolean search(String word) returns true if word was previously inserted.

- boolean startsWith(String prefix) returns true if any inserted word begins with prefix.

Example 1:

Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]

Example 2:

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
1 of 4
1:00

What is the optimal approach for this problem?