Skip to content
Trie: A Prefix Tree
step 1/5

Reading — step 1 of 5

Read

~1 min readBuilding the Trie

Trie: A Prefix Tree

A trie stores strings sharing common prefixes by sharing tree nodes.

Words: cat, car, cart, dog

         (root)
        /      \
       c        d
       |        |
       a        o
      / \       |
     t   r      g
     *   |   (* = end of word)
         (also a path to cart...)

Each path from root to a marked node is a word. Common prefixes share branches (cat and car both go through c->a).

Compared to a hash set:

  • Hash set: O(1) lookup; can't enumerate prefixes.
  • Trie: O(m) lookup (m = word length); easy prefix queries.

Tries are fast for "all words starting with pre" — walk down to pre (m steps), then DFS the subtree.

Used in:

  • Autocomplete (search bars, IDEs)
  • Spell checkers (with edit-distance walks)
  • IP routing tables (longest-prefix match)
  • Dictionary structures

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…