A trie (prefix tree) stores strings character by character so that all words sharing a prefix share a path. It powers autocomplete, spell-checkers and IP routing: checking whether any stored word starts with a prefix costs only O(len(prefix)), no matter how many words are stored.
Build the word store behind a search box's autocomplete as a class Trie:
Trie()starts with no words.insert(word)addswordto the store.search(word)answersTrueonly ifworditself was inserted earlier, andFalseotherwise.starts_with(prefix)answersTrueif at least one inserted word begins withprefix, andFalseotherwise. Every word begins with itself, so afterinsert("cat")the callstarts_with("cat")isTrue.
Examples
Input:
Trie()
insert("plan")
insert("planet")
search("plane") -> False (so far only a prefix of "planet")
starts_with("plane") -> True
search("plan") -> True
starts_with("plot") -> False
insert("plane")
search("plane") -> True
Output: [None, None, None, False, True, True, False, None, True]
Constraints
- Words and prefixes consist of lowercase letters, length
1..100 - At most 1000 calls in total
Goals
- Represent a trie as nested dictionaries, one level per character
- Mark the end of a word separately from the existence of a prefix
- Share a private helper between two public methods