Skip to content

What is a Trie?

Data Structures·5 min·Python code

Tries, known as prefix trees, store strings one character per node, so every word is a path from the root. Insert, search and prefix checks cost O(L) for a word of length L, no matter how many words you store.

Trie Prefix Tree Basics

Think of paper dictionaries. You do not check every entry to find queue. You open at q, then u, then e. Every letter narrows the search, and words with shared beginnings sit together.

Tries rebuild that dictionary as a tree. Roots hold the empty string, and every edge is a character. Walking down from the root spells a prefix, and a flagged node says a real word ends there.

Words that start the same way share nodes until they differ. Queue and query share que, then split after it.

How a Trie Stores and Searches Words

Nodes hold two things, a map from the next character to a child node and a flag that says a word ends here. Insert walks the word character by character, creates a child whenever one is missing and sets the flag on the last node.

Search repeats the same walk without creating anything. If a character has no child, the word is not stored.

Search and prefix search differ only in the last line. Search needs the end of word flag, while prefix search succeeds the moment the walk reaches a node. Both walks use tree style steps, one level per character.

Trie vs Hash Table for Prefix Search

Hash tables answer one question well, which is whether an exact string exists. They hash the full string, so they cannot list the words that start with que. Compare that with the hash table guide.

Tries keep the structure of the prefix, so they answer a family of questions. They list every word behind a prefix for autocomplete, find the longest stored prefix of a string for routing or word break and return words in alphabetical order when you visit children in order.

Search boxes, spell checkers and routers rely on that. Practise on CodeStory's trie practice problems.

Trie Code Example in Python

pythonTrie in Python with insert, search and prefix search.

class TrieNode:
    def __init__(self):
        self.children = {}      # character -> TrieNode
        self.is_word = False    # a word ends at this node


class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        node = self.root
        for ch in word:                      # one step per character
            node = node.children.setdefault(ch, TrieNode())
        node.is_word = True

    def _walk(self, prefix):
        node = self.root
        for ch in prefix:
            if ch not in node.children:
                return None                  # the path ends early
            node = node.children[ch]
        return node

    def search(self, word):                  # is the full word stored?
        node = self._walk(word)
        return node is not None and node.is_word

    def starts_with(self, prefix):           # does any word start with it?
        return self._walk(prefix) is not None

Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App

Trie Time and Space Complexity

TimeO(L) per insert, search or prefix check, where L is the word length
SpaceO(N x L) in the worst case for N words of length L, and less when words share prefixes

Stored word count never enters the cost. Tries with ten words and tries with ten million words answer a five character lookup in the same five steps.

When to Use a Trie

  • You build autocomplete or search suggestions and need every word behind a prefix.
  • You check many words against a dictionary, like in word break or a spell checker.
  • You match the longest prefix, the way a router selects a route for an address.
  • You solve word games and puzzles, like Boggle and crosswords, where you prune a path the moment no word can follow.

Mistakes to Avoid

  • Ignoring memory. One node per character weighs far more than a hash set holding the same words.
  • Using a trie for exact lookups only. If you never ask about prefixes, a hash set is simpler and quicker.
  • Allocating 26 children per node for large alphabets like Unicode. Maps waste less space.
  • Expecting sorted or range queries over full strings. Balanced trees fit those better.

Trie FAQs

What is the time complexity of a trie?

O(L) for all three operations, where L is the word length. Stored word count does not change the cost.

Should I use a trie or a hash table?

Choose a hash table for exact lookups, since it needs less memory and shorter code. Choose a trie the moment you ask about prefixes, because it keeps the shared beginning of words as structure.

How much memory does a trie use?

One node per character on every distinct path, plus the map inside every node. Shared prefixes are stored once, so a dictionary of related words costs less than it looks. Unrelated words cost more.

Which interview problems use a trie?

Implement Trie, Word Search II, Word Break, Replace Words, Longest Common Prefix and autocomplete style design questions.

What is the difference between a trie and a prefix tree?

Nothing. Prefix tree is another name for a trie, and both names describe trees where words are paths of characters.

How do I mark where a word ends in a trie?

Set a flag on the last node of the word, named is_word in the code above. Without the flag, que could not be told apart from the start of queue.

How do I practise tries on CodeStory?

Write insert, search and prefix search yourself in the browser IDE, then try CodeStory's trie practice problems.

Related Guides

Guides are step one. In a CodeStory batch you code the trie yourself, then explain every node in a scored mock round.

Talk to a Mentor

Stuck on Tries? Get a Free Callback

Tell CodeStory which trie step confuses you, and a mentor shapes your next steps.

  1. 1CodeStory finds your starting point, from your first node to interview ready.
  2. 2CodeStory explains online and campus batches, with timings for your mornings or evenings.
  3. 3You decide. No pressure, no payment on the call.

Get a Free Callback

I am a
I want to learn

CodeStory dials your number only for this callback.