Advanced topics · Exercise 87 of 100

Trie (prefix tree)

A trie stores words as paths from a shared root, with one letter on each edge. To insert a word, follow the edges for its letters and create a child only when the next edge is missing. Mark the last node so a search can tell a stored word from a prefix.

Try it yourself

Start with just the root and insert map, mat and mop. How many nodes are there besides the root?

One-step hint

Sketch one path per word, branching only where the next letter differs. Count each distinct nonempty prefix once, even if several words share it.

Worked solution
  1. Inserting map creates nodes for m, ma and map. The word mat follows the same path through ma and adds one node for mat.
  2. The word mop reuses m and adds nodes for mo and mop, bringing the count to 6.
DSA compiler