Implement Trie
Store words in a prefix tree so you can check whole words and prefixes in time proportional to their length.
The problem
Design a class Trie that stores lowercase words. Trie() creates an empty trie. insert(word) adds a word. search(word) returns True if that exact word was inserted, otherwise False. startsWith(prefix) returns True if at least one inserted word begins with prefix, otherwise False. Words can be up to 2,000 letters long, and there can be tens of thousands of operations.
Starter code
class Trie:
def __init__(self):
passPublic examples
obj = Trie() obj.insert("apple") obj.search("apple") obj.search("app") obj.startsWith("app") obj.insert("app") obj.search("app")gives[None, None, True, False, True, None, True]obj = Trie() obj.insert("car") obj.insert("cat") obj.search("car") obj.startsWith("ca") obj.search("cap")gives[None, None, None, True, True, False]obj = Trie() obj.insert("a") obj.search("a") obj.startsWith("a") obj.search("b")gives[None, None, True, True, False]
Solving it in the practice book needs an active paid plan.
Open it in the practice bookOne thought at a time.
