Browse curriculum

Trie (Prefix Tree)

A trie (prefix tree) is a tree-based data structure for efficiently storing and retrieving keys in a dataset of strings.

GREEN = END OF A STORED WORD

READY

 

Insert words and watch shared prefixes get reused. A node marked as a word end is what separates a stored word from a mere prefix.

 

Word

Intuition

Think of a dictionary where you look up words letter by letter. A Trie (pronounced 'try') stores strings such that common prefixes are shared. For example, 'cat' and 'car' share the path 'c' -> 'a'.

Concept

Each node in a Trie represents a character. The root represents an empty string. Moving down from the root adds characters to the prefix. Some nodes are marked as endOfWord to indicate that the path from the root to that node forms a valid word.

How it Works

  • Root: Empty node, starting point.
  • Children: Map or array linking characters to next nodes.
  • EndOfWord: Boolean flag marking a complete string.
  • Insertion: Walk down, creating nodes if they don't exist.
  • Search: Walk down; if you get stuck, word doesn't exist.

Step-by-Step Breakdown

Insertion Logic:
  1. Start at root.
  2. For each character in the word:
    • Check if child exists for that char.
    • If not, create a new node.
    • Move to child.
  3. Mark the final node as isEnd = true.

When to Use

  • Autocomplete/Typeahead systems.
  • Spell checkers.
  • IP routing (Longest Prefix Match).
  • Solving word games (Boggle).

When NOT to Use

  • When strings are very long and unique (high space consumption).
  • When you only need full string matching: a hash set is simpler and usually faster in practice. Both take O(L) per lookup, since hashing a string reads every character, but a hash set has no per-character pointer chasing.

How to Identify

Keywords: "Prefix search", "Autocomplete", "Dictionary", "Word Search II".

Preparing for interviews? This topic is also taught as a pattern:

Introduction to Tries (Prefix Trees)

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

When to use a Trie?

Tries are ideal for prefix matching, autocomplete features, spell checkers, and IP routing where string keys share common prefixes.


Trie vs Hash Map performance?

Tries can be faster for prefix searches and avoid hash collisions. However, they use significantly more memory due to many node pointers.


How is Autocomplete implemented?

Autocomplete works by traversing the Trie to the prefix node and then finding all words in its subtree (usually via DFS).