Implement Trie (Prefix Tree) (LeetCode 208): Solution and Explanation

Medium
Hash Table
String
Design
Trie

Build a prefix tree that supports three operations: insert a word, check whether an exact word was inserted, and check whether any inserted word starts with a given prefix.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The obvious design is to keep the words in a hash set. Exact lookups are then fast, but prefix queries are not: to answer startsWith, you would have to compare the prefix against every stored word, which costs time proportional to the whole dictionary.

A trie flips the storage around so that shared prefixes are stored once. Each node represents the string spelled by the path from the root to it, and its children are the possible next characters. The words apple and app share the nodes for a, p and p, and only branch after that. With this shape, answering whether anything starts with a prefix is just walking down the tree one character at a time, and the cost depends only on the length of the prefix, not on how many words are stored.

The one detail that trips people up is telling a full word apart from a prefix. After inserting apple, the path for app exists in the tree, but app was never inserted. So each node carries an is_end flag that is set only on the last node of an inserted word. Search walks the path and then checks that flag, while startsWith only needs the path to exist.

The reference code stores children in a dictionary keyed by character. That handles any alphabet and only allocates entries for characters that actually appear. A fixed array of 26 slots is a common alternative when the input is lowercase letters only.

Approach: Trie with dictionary children

  1. Define TrieNode with a children dictionary and an is_end flag set to false, and give the Trie an empty root node.
  2. For insert, start at the root and, for each character, create a child node if it is missing, then move into it.
  3. After the last character of the word, set node.is_end = True to mark that a complete word ends there.
  4. For search, walk the same way, returning false as soon as a character has no child, and at the end return node.is_end.
  5. For startsWith, walk the prefix the same way, but return true once every character is matched, regardless of the flag.

Step-by-step example

insert(apple), search(apple), search(app), startsWith(app), insert(app), search(app)
  1. insert(apple) creates the chain a, p, p, l, e under the root and marks the e node with is_end = True.
  2. search(apple) follows all five characters and reaches the e node, whose flag is true, so it returns true.
  3. search(app) follows a, p, p and stops at the second p node. Its flag is false, so it returns false.
  4. startsWith(app) follows the same three nodes successfully and returns true without checking the flag.
  5. insert(app) walks the existing a, p, p nodes without creating anything and sets the flag on the second p node.
  6. search(app) now reaches a node whose flag is true and returns true.

Code: Python, Java, C++

1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.is_end = False
5
6class Trie:
7    def __init__(self):
8        self.root = TrieNode()
9
10    def insert(self, word: str) -> None:
11        node = self.root
12        for char in word:
13            if char not in node.children:
14                node.children[char] = TrieNode()
15            node = node.children[char]
16        node.is_end = True
17
18    def search(self, word: str) -> bool:
19        node = self.root
20        for char in word:
21            if char not in node.children:
22                return False
23            node = node.children[char]
24        return node.is_end
25
26    def startsWith(self, prefix: str) -> bool:
27        node = self.root
28        for char in prefix:
29            if char not in node.children:
30                return False
31            node = node.children[char]
32        return True

Time and space complexity

Time

O(L) per operation

Each of insert, search and startsWith does one dictionary lookup or insertion per character of its input, where L is the length of the word or prefix. The number of stored words does not matter.

Space

O(T)

T is the total number of characters across all inserted words. In the worst case no prefixes are shared and every character gets its own node; shared prefixes reduce this.

Other approaches

Fixed array of 26 children (time O(L) per operation, space O(26 × T))

Give each node an array of 26 child slots indexed by ord(ch) - ord('a'). Lookups avoid hashing and are slightly faster, but every node reserves 26 slots even if it only has one child, so memory use is higher.

Hash set of words and prefixes (time O(L²) insert, O(L) query, space O(sum of L²))

Store each word in one set and every prefix of every word in another. Queries become single set lookups, but inserting a word of length L stores L prefix strings with a combined length of O(L²).

Common mistakes

  • Returning true from search just because the path exists. Without checking is_end, a search for app succeeds after inserting only apple.
  • Setting is_end on every node along the path during insert, which makes every prefix look like an inserted word.
  • Creating a new node even when the child already exists, which overwrites an existing subtree and silently deletes previously inserted words.
  • Checking is_end in startsWith. A prefix query should succeed whenever the path exists, whether or not a word ends there.

Frequently asked questions

What is the difference between search and startsWith in a trie?

Both walk the tree character by character. search also requires that the final node is marked as the end of a word, while startsWith only requires that the path exists.

What is the time complexity of a trie?

Insert, search and prefix search all run in O(L), where L is the length of the input string. They do not depend on how many words the trie holds.

Should trie children be a hash map or an array?

An array of 26 is a bit faster for lowercase English and simple to index, but it wastes memory on sparse nodes. A hash map handles any character set and only stores children that exist.

When is a trie better than a hash set?

When you need prefix queries, autocomplete or wildcard matching. A hash set answers exact lookups well but has no efficient way to find all words that share a prefix.