AlgoMaster Logo

Introduction to Trie

High Priority13 min readUpdated November 9, 2026
Listen to this chapter
Unlock Audio

Premium Video

This video is available to premium subscribers only

Unlock Full Access

A trie, also known as a prefix tree, is a special type of tree data structure designed to store and search strings efficiently by reusing common prefixes.

You have probably used tries many times without realizing it. When a search engine suggests queries as you type, when your phone autocorrects a word, or when your code editor offers autocomplete, there is a good chance a trie is doing the work.

Tries are also an important topic in coding interviews, especially when a problem involves prefix-based search or efficient string lookups.

In this chapter, we will cover:

  • What a trie is and how it stores words
  • The structure of a TrieNode
  • How to implement the insert, search, and prefix search operations
  • How autocomplete works on a trie
  • How a trie compares to a HashSet
  • When to use a trie in a coding interview

What is a Trie?

Think about how you look up a word in a printed dictionary.

You don't go through every word one by one. Instead, you start with the first letter, then narrow your search using the second letter, the third, and so on. Words that begin with the same letters naturally appear together.

A trie follows a similar idea. Instead of storing every word separately, it organizes words character by character, allowing words with common prefixes to share the same path.

Let's say we want to store three words in a trie: "design", "desktop", and "destination".

We'll start with "design". We insert it one character at a time, creating a chain of nodes for d, e, s, i, g, and n.

rootdesign

Following the path from the root to n spells out the word "design".

Next, let's insert "desktop".

Notice that both "design" and "desktop" begin with the same three characters: d, e, and s. Instead of creating a completely new path, we reuse these existing nodes. Then, since the next character is different, we create a new branch and continue adding the remaining characters k, t, o, and p.

rootdesikgtnop

Finally, let's insert "destination".

Once again, we start by following the existing path for d, e, and s. From there, we create a new branch for the remaining characters.

rootdesiktgtinonpation

And that's the key idea behind a trie. Words with common prefixes share the same path, and new branches are created only when their characters differ.

We also mark the last character of each word with a special flag to show where a complete word ends. This matters because a path can exist without being a word. In the trie above, the path d → e → s → k exists because it is part of "desktop", but "desk" is not a stored word. Only the flag on the last node tells the two apart.

To summarize:

  • Each node represents a single character.
  • A path from the root to a marked node represents a complete word.
  • Words that share a prefix share the same starting path.

The Structure of a TrieNode

Now let's see how a trie is actually represented in code. It all starts with a single building block: the TrieNode.

Each TrieNode has two main parts:

  1. Children: a collection of child nodes, representing the possible characters that can come next.
  2. isEndOfWord: a boolean flag that tells us whether a complete word ends at that node.

The trie itself starts with a single root node, which is initially empty. Whenever we insert a word, we start at the root and move down the trie, one character at a time, creating new nodes whenever necessary.

In our earlier example, the nodes for d → e → s are shared by all three words. After s, the trie branches into separate paths for "design", "desktop", and "destination", and the last node of each path has isEndOfWord set to true.

Array vs Hash Map for Children

There are two common ways to store a node's children.

The first is an array of fixed size, like 26, with one position for each lowercase English letter. The child for character c lives at index c - 'a'. This gives us fast, direct access to child nodes. However, it only works for a fixed alphabet and can waste memory when most positions are unused.

The second approach is a hash map, where each character maps to its corresponding child node. This is more flexible because we only store children that actually exist, and we can support a much larger set of characters. The trade-off is some additional overhead from hashing.

So which one should you use?

  • In coding interviews, if the problem only involves lowercase English letters, an array is usually the simplest choice.
  • If the character set is larger or unknown, a hash map is generally a better option.

The Java code in this chapter uses the array approach. The other languages use a hash map, so you can see both styles side by side.

Trie Operations

Let's look at the most common operations in a trie, starting with insert.

1. Insert

Let's say we want to insert the word "design" into an empty trie.

  1. We start at the root and look at the first character, d.
  2. Since the root doesn't have a child for d, we create a new node and move to it.
  3. Next, we look at e. Again, there's no existing child for this character, so we create one and move forward.
  4. We continue this process for the remaining characters: s, i, g, and n.
  5. Once we've inserted all the characters, we mark the last node, n, by setting its isEndOfWord flag to true.

This tells us that the path we've just created represents a complete word: "design".

rootdesign

Now let's insert the word "desktop".

  1. We start at the root and look at the first character, d.
  2. This time, a child node for d already exists from when we inserted "design", so we simply move to that node.
  3. The same goes for e and s. We follow the existing path without creating any new nodes.
  4. When we reach k, there's no matching child, so we create a new node.
  5. We continue adding the remaining characters: t, o, and p.
  6. Once we reach the last character, p, we mark that node as the end of a word.
rootdesikgtnop

Notice that we didn't need to create new nodes for d, e, and s. We simply reused the existing ones.

That's how prefix sharing works in a trie. Instead of storing common prefixes repeatedly, we store them once and reuse them across multiple words.

Here is how we can implement the insert operation in code:

We start at the root node. For each character in the word, we check whether a child node for that character already exists. If it doesn't, we create a new TrieNode. Then, we move to that child node and repeat the process for the next character.

Once we've processed all the characters, we set the isEndOfWord flag of the final node to true, indicating that a complete word ends here.

Time complexity: O(L), where L is the length of the word, because we process each character exactly once.

Space complexity: O(L) in the worst case, since we might need to create a new node for every character. However, if some prefixes already exist in the trie, we reuse those nodes and save memory. Inserting "desktop" after "design" creates only 4 new nodes, not 7.

Next, let's see how we can search for a complete word in a trie.

The search operation is very similar to insertion, except we don't create any new nodes.

We start at the root and follow the path one character at a time. For each character, we check whether the corresponding child node exists. If it doesn't, we immediately return false because the word isn't present in the trie.

If we successfully reach the end of the word, we check the isEndOfWord flag of the final node. If it's true, the word exists in the trie. Otherwise, we return false.

This final check is important because a path can exist in the trie without representing a complete word. In a trie that holds "design" and "desktop", searching for "desk" walks all the way to k, but k is not marked as the end of a word, so the search returns false.

The walk lives in a small helper called find. It returns the node for the last character, or null if the path breaks. We will reuse it for prefix search next.

Time complexity: O(L), where L is the length of the word we're looking for.

The interesting part is that it doesn't matter whether the trie contains ten words or ten million. The time it takes to search for a word depends only on its length, not on the total number of words stored.

Space complexity: O(1) extra space, since we only need a pointer to track our current node.

3. Prefix Search (startsWith)

Now let's look at one of the most powerful features of a trie: prefix search. This is what makes tries especially useful for features like autocomplete.

We use the helper method find, which starts at the root and follows the path one character at a time. If a required child node doesn't exist, it returns null. Otherwise, it returns the node corresponding to the last character.

Our startsWith method simply checks whether find returns a valid node.

Notice that we don't need to check the isEndOfWord flag here. That's because we're not looking for a complete word. We only want to know whether the prefix exists.

And if it does, every word in the subtree rooted at that node shares the same prefix. For example, startsWith("des") returns true for a trie holding "design" and "desktop", even though "des" itself is not a stored word.

Time complexity: O(L), where L is the length of the prefix. Space complexity: O(1).

Autocomplete Walkthrough

Let's see how autocomplete works with an example.

Suppose we insert six words into our trie: "design", "desire", "desk", "desktop", "deal", and "dog".

rootdeosagiklgrtneop

Now, imagine a user types "des", and we want to suggest all the words that start with this prefix.

  1. We start at the root and follow the path for d, e, and s.
  2. Once we reach the node for s, we perform a Depth-First Search on the subtree rooted at that node.
  3. As we explore the subtree, we collect every word whose final node has isEndOfWord set to true.

In this case, we find four matching words: "design", "desire", "desk", and "desktop". The branches for "deal" and "dog" are never visited, because they sit outside the subtree under s.

Here is the code:

autocomplete first calls find to locate the prefix node. Then collectWords runs a depth-first search from that node, adding the current string to the results every time it reaches a node with isEndOfWord set to true. In the Java and Python versions, children are visited in alphabetical order, so the results come back sorted: ["design", "desire", "desk", "desktop"].

That's the basic idea behind autocomplete using a trie. We first locate the prefix, then explore its subtree to find all matching words, without searching through the entire dictionary.

Time complexity: O(P + M), where P is the length of the prefix and M is the total length of the matching words we retrieve.

Trie vs HashSet

Now, you might be wondering: can't we use a HashSet for fast lookups too?

Yes, absolutely. A HashSet can check whether a word exists in O(L) expected time, where L is the length of the word.

But here's the difference. A HashSet is great for exact lookups, but it doesn't support prefix searches efficiently.

Suppose we want to find every word that starts with "des".

  • With a HashSet, we'd need to go through every stored word and check whether it starts with that prefix.
  • With a trie, we can simply follow the path for "des" and explore the subtree to find all matching words.

The time depends on the length of the prefix and the total length of the matching words we retrieve, rather than the size of the entire dictionary.

Scroll

Feature

Trie

HashSet

Exact lookup of a word of length L

O(L)

O(L) expected (hashing the word)

Does a word start with a prefix?

O(P)

Scan every stored word

All words with a prefix

O(P + M)

Scan every stored word

Memory

Higher (one node per character, plus child links)

Lower (one entry per word)

Words that share a prefix

Prefix stored once

Each word stored in full

Here P is the prefix length and M is the total length of the matching words.

And that's the main trade-off. Tries typically require more memory to maintain their tree structure, but in return, they make prefix-based operations much more efficient.

When to Use a Trie

So, when should you consider using a trie in a coding interview? There are a few common patterns to look out for.

1. Prefix-based problems

Whenever a problem involves finding words with a common prefix, checking whether a prefix exists, or counting how many words start with a particular string, a trie is worth considering.

2. Autocomplete and search suggestions

Tries make it easy to find all the stored words that begin with a given prefix, as we saw in the autocomplete walkthrough.

3. Word games and puzzles

Another common use case is word games and puzzles, like Boggle or Word Search. In these problems, we often need to find dictionary words hidden in a grid of characters. A trie helps us explore possible words efficiently by stopping as soon as we encounter a prefix that doesn't exist in our dictionary.

Finally, there's wildcard word search, where certain characters can match any letter. By combining a trie with Depth-First Search, we can explore the possible matches without checking every word individually.

Summary

  • A trie stores words character by character, so words with a common prefix share the same path.
  • Each TrieNode holds its children and an isEndOfWord flag that marks where a complete word ends.
  • Insert, search, and prefix search all run in O(L) time, where L is the length of the word or prefix, no matter how many words the trie holds.
  • Prefix search is where tries stand out. A HashSet answers exact lookups just as fast, but it cannot find words by prefix without scanning everything.

To really understand these concepts, try implementing the three core operations yourself: insertion, search, and prefix search.

Quiz

Introduction to Trie Quiz

10 quizzes