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:
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.
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.
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.
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:
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:
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.
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?
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.
Let's look at the most common operations in a trie, starting with insert.
Let's say we want to insert the word "design" into an empty trie.
d.d, we create a new node and move to it.e. Again, there's no existing child for this character, so we create one and move forward.s, i, g, and n.n, by setting its isEndOfWord flag to true.This tells us that the path we've just created represents a complete word: "design".
Now let's insert the word "desktop".
d.d already exists from when we inserted "design", so we simply move to that node.e and s. We follow the existing path without creating any new nodes.k, there's no matching child, so we create a new node.t, o, and p.p, we mark that node as the end of a word.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.
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).
Let's see how autocomplete works with an example.
Suppose we insert six words into our trie: "design", "desire", "desk", "desktop", "deal", and "dog".
Now, imagine a user types "des", and we want to suggest all the words that start with this prefix.
d, e, and s.s, we perform a Depth-First Search on the subtree rooted at that node.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.
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".
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.
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.
So, when should you consider using a trie in a coding interview? There are a few common patterns to look out for.
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.
Tries make it easy to find all the stored words that begin with a given prefix, as we saw in the autocomplete walkthrough.
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.
isEndOfWord flag that marks where a complete word ends.To really understand these concepts, try implementing the three core operations yourself: insertion, search, and prefix search.
10 quizzes