Learn / Tries

Insert, search and prefix

A trie stores words letter by letter in a tree, so words with a common beginning share a path. Inserting or looking up a word takes one step per letter, whatever the number of words, and 'does any word start with this?' is just a walk down the prefix.

How to recognise it

  • Many words and questions about prefixes.
  • Autocomplete: every word starting with what has been typed.
  • The shortest prefix that tells one word apart from the others.
cdaort
Words: car, cat, do. car and cat share the path c then a. Filled nodes end a word; every word through the a node starts with ca.

The structure page shows the trie on its own; this lesson is about using it.

The three operations

insert(w):  node = root; for c in w: node = node.child[c] (create if missing); node.end = true
search(w):  walk w; true if the walk finishes and node.end
prefix(p):  walk p; true if the walk finishes

Counts on the nodes

Keep pass (words through the node) and end (words ending there) to answer "how many words equal w" and "how many start with p", and to erase a word by decreasing both along its path.

ProblemWhat the trie gives
implement a trieinsert, search, starts-with
counts and erasepass and end counters
shortest unique prefixthe first node on a word's path with pass = 1
phone directorythe subtree under each typed prefix, read in letter order
unique rowsa binary trie: a row that creates a new node was not seen before

Common mistakes

  • Treating a prefix as a stored word (forgetting end).
  • Creating nodes during a search.

Problems

0 of 5 solved

Check yourself

How long does looking up a word of length L take?

Why does a node need an 'end' flag?

To count the words starting with a prefix, what does each node store?

Collecting the words under a node in alphabetical order needs?