Profile

Unblock all features

Sign in to track progress and visualise your code.

ntree.ai
Linked lists, trees and graphs

Trie

A trie, or prefix tree, is a tree that stores words letter by letter. Every node is one letter, and the path from the root to a node forms a word. This way words that share a prefix share its nodes.

That is why tries are helpful when you need to find words by their prefix.

c
a
r
t
t
d
o
g
car, cart, cat, do and dog, where ✓ marks the end of a word

Time complexity

operationtime
insert a word of length mO(m)O(m)
search a word of length mO(m)O(m)
check a prefix of length mO(m)O(m)

Implementation

Nodes

Every node should keep a map from a letter to its child and a flag that says whether a word ends at this node.

The root is a node without a letter.

Insert a word

Insert traverses the tree from the root letter by letter.

When the current node has no child for the next letter, we need to create one. The node of the last letter gets its flag set.

insert cap
c
a
r
t
c exists, move to c
1 / 5

Search prefix or word

Search traverses the tree from the root letter by letter.

If every letter has a node, the prefix is found. To search for a word, we also need to check the flag of the last node.

search cat
c
a
p
r
t
c exists, move to c
1 / 4

Build it

Implement insert, search and starts_with in the class below.

Build a trie
Python
# Definitions:
# class TrieNode:
# def __init__(self):
# self.children = {}
# self.is_word = False
class Trie:
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word: str) -> None:
# Add the word to the trie
pass
def search(self, word: str) -> bool:
# Return True when the word was inserted
return False
def starts_with(self, prefix: str) -> bool:
# Return True when an inserted word starts with the prefix
return False
trie = Trie()
for word in ["cat", "car", "dog"]:
trie.insert(word)
print(trie.search("dog"), trie.search("cow"), trie.starts_with("ca"))
Was this lesson helpful?