What is Trie
Insert a list of lowercase words into a trie. Then answer queries. S word returns 1 when that exact word was inserted. P word returns 1 when some inserted word starts with that prefix.
Example. Insert app, apple, and apt. S app and S apple are words. P ap is a prefix. S ape is not a stored word.
Words: app apple apt Queries: S app, S apple, P ap, S ape Output: 1 1 1 0
Constraints. Up to 1000 words and 1000 queries, each of length at most 20. This picture draws 4 words, 4 queries, and 6 letters each.
Approach
Words that share a beginning, such as app and apple, share the same nodes. The brighter nodes in the picture are word ends.
Interactive solution
The finished structure is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Insert / query | O(L) | L is the length of that word. Each letter is one edge. |
| Space | O(total letters) | Shared prefixes store each edge once. |
Implementation
def insert(self, word):
node = self.root
for ch in word:
node = node.setdefault(ch, {})
node["#"] = True
def search(self, word):
node = self._walk(word)
return node is not None and node.get("#", False)
def starts_with(self, prefix):
return self._walk(prefix) is not None