Data Structures & Algorithms / Module 6: Trees

Topic 6.5

Tries

Words stored letter by letter, which makes prefix search and autocomplete cheap.

9 min · intermediate

Watch: every step down is one letter. Words that start the same share the same path.

rootcdaortgt
  • being checked
  • passed / marked
  • finished / the result
Step 1 of 5

A trie holding car, cart, cat, do, dog. Each node is one letter; words that start the same share a path. Is "cat" in it?

Looking up a word takes one step per letter, no matter how many words are stored.

Like a thick dictionary

Looking up "kitten" in a paper dictionary: open the K section, then find words starting with "ki", then "kit". Each letter narrows down the pages to look at. A trie works exactly like that, except each letter takes you straight to the right branch, with no page-flipping.

Word ends need a marker

Choose "word ca" in the figure. The c-a path exists, because car and cat pass through it, but "ca" itself was never stored. That's why every node has a "a word ends here" marker. Without it, a trie couldn't tell a stored word from the start of another word. "do" and "dog" are both stored: the "o" node is marked, and the path still carries on to "g".

Code, for programmersA simple trie
class Trie {
  root = { children: new Map(), end: false };

  insert(word) {
    let node = this.root;
    for (const ch of word) {
      if (!node.children.has(ch)) node.children.set(ch, { children: new Map(), end: false });
      node = node.children.get(ch);
    }
    node.end = true;                    // mark: a stored word ends here
  }

  startsWith(prefix) {                  // every stored word that begins with prefix
    let node = this.root;
    for (const ch of prefix) {
      node = node.children.get(ch);
      if (!node) return [];             // no branch: nothing starts this way
    }
    const out = [];
    const collect = (n, word) => {
      if (n.end) out.push(word);
      for (const [ch, child] of n.children) collect(child, word + ch);
    };
    collect(node, prefix);
    return out;
  }
}

Where you meet it

  • Autocomplete in search boxes and code editors.
  • Routers in web frameworks: /api/users/:id and /api/users/me share the prefix /api/users/. Routers like find-my-way (Fastify) use this kind of prefix tree.
  • IP routing: network routers look for the longest matching address prefix.
  • Spell checkers and word filters.

Quiz

  1. A trie holds 1 million words. How many steps to check the word 'tea'?

  2. Why do nodes need a 'word ends here' marker?

  3. When is a hash set a better fit than a trie?

0 of 3 answered.