Pattern 21 of 22

Trie Pattern: Template + 49 LeetCode Problems

Store a set of words by their shared prefixes so lookups cost the length of the word.

Easy
3
Medium
24
Hard
22

What the trie pattern is

A trie stores a set of strings as a tree in which each edge is one character and each path from the root spells a prefix, so words sharing a prefix share the nodes that spell it. Lookup and insertion cost the length of the word and nothing else — the size of the dictionary does not appear in the complexity, which is why a trie beats a hash set for every question about prefixes rather than whole words. The node needs exactly two things: a map from character to child, and a flag saying a word ends here, because "car" being present must be distinguishable from "car" merely being a prefix of "cart". Two extensions cover most of the harder problems: storing a count or the best word at each node answers autocomplete queries without walking the subtree, and pairing a trie with a backtracking search over a grid prunes whole regions the moment the prefix stops existing, which is what makes a word-search-over-a-dictionary tractable.

When to use it

  • Queries are about prefixes: autocomplete, "does any word start with…", longest common prefix.
  • A large dictionary is searched many times and repeated prefix work is the bottleneck.
  • A backtracking search over a grid or a string needs to be pruned by a word list.
  • Wildcards must be matched inside words, where a hash set cannot help at all.

The trie template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 49 problems listed below.

PythonTrie template
class Trie:
    def __init__(self):
        self.children = {}
        self.is_word = False       # "car" present vs. "car" merely a prefix of "cart"

    def insert(self, word):
        node = self
        for char in word:
            node = node.children.setdefault(char, Trie())
        node.is_word = True

    def find(self, prefix):
        """The node reached by prefix, or None. is_word tells you if it is a word."""
        node = self
        for char in prefix:
            node = node.children.get(char)
            if node is None:
                return None
        return node

Complexity characteristics

Time
O(L) per insert or lookup, where L is the length of the word
Auxiliary space
O(total characters stored)

The cost of a lookup is the length of the key and nothing else — the number of words already stored does not appear in it, which is the property a hash set cannot match for prefix queries. The space is one node per distinct prefix, so a dictionary with heavy prefix sharing costs far less than the sum of its word lengths and one with none costs exactly that sum. Pairing a trie with a grid search prunes the moment a prefix stops existing, which changes the observed cost by orders of magnitude without changing the worst case.

Eyes only

Meet the trie problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 49 trie LeetCode problems

Every problem in the library the trie pattern applies to, grouped by LeetCode's own difficulty rating. 36 of the 49 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Related LeetCode topics

Easy (3)

Easy problems
No.Problem
0014Longest Common Prefix
1065Index Pairs of a StringPremium
2932Maximum Strong Pair XOR I

Medium (24)

Medium problems
No.Problem
0139Word Break
0208Implement Trie (Prefix Tree)
0211Design Add and Search Words Data Structure
0386Lexicographical Numbers
0421Maximum XOR of Two Numbers in an Array
0648Replace Words
0676Implement Magic Dictionary
0677Map Sum Pairs
0692Top K Frequent Words
0720Longest Word in Dictionary
1268Search Suggestions System
0616Add Bold Tag in StringPremium
0758Bold Words in StringPremium
0792Number of Matching Subsequences
0820Short Encoding of Words
1023Camelcase Matching
1166Design File SystemPremium
1233Remove Sub-Folders from the Filesystem
1698Number of Distinct Substrings in a StringPremium
1804Implement Trie II (Prefix Tree)Premium
1858Longest Word With All PrefixesPremium
2261K Divisible Elements Subarrays
2452Words Within Two Edits of Dictionary
2707Extra Characters in a String

Hard (22)

Hard problems
No.Problem
0140Word Break II
0212Word Search II
0336Palindrome Pairs
0440K-th Smallest in Lexicographical Order
0472Concatenated Words
0745Prefix and Suffix Search
0425Word SquaresPremium
0527Word AbbreviationPremium
0588Design In-Memory File SystemPremium
0642Design Search Autocomplete SystemPremium
1032Stream of Characters
1178Number of Valid Words for Each Puzzle
1316Distinct Echo Substrings
1707Maximum XOR With an Element From Array
1803Count Pairs With XOR in a Range
1938Maximum Genetic Difference Query
1948Delete Duplicate Folders in System
2227Encrypt and Decrypt Strings
2416Sum of Prefix Scores of Strings
2479Maximum XOR of Two Non-Overlapping SubtreesPremium
2935Maximum Strong Pair XOR II
2977Minimum Cost to Convert String II

Trie pattern FAQ

What is the trie pattern?

A trie stores a set of strings as a tree in which each edge is one character and each path from the root spells a prefix, so words sharing a prefix share the nodes that spell it.

How many LeetCode problems use the trie pattern?

This page lists 49 LeetCode problems that the trie pattern applies to: 3 Easy, 24 Medium and 22 Hard. 36 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the trie pattern?

O(L) per insert or lookup, where L is the length of the word time and O(total characters stored) space. The cost of a lookup is the length of the key and nothing else — the number of words already stored does not appear in it, which is the property a hash set cannot match for prefix queries. The space is one node per distinct prefix, so a dictionary with heavy prefix sharing costs far less than the sum of its word lengths and one with none costs exactly that sum. Pairing a trie with a grid search prunes the moment a prefix stops existing, which changes the observed cost by orders of magnitude without changing the worst case.

When should I use the trie pattern in an interview?

Queries are about prefixes: autocomplete, "does any word start with…", longest common prefix. A large dictionary is searched many times and repeated prefix work is the bottleneck.

Which trie problem should I start with?

LeetCode 14. Longest Common Prefix is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to trie?

Hash Map, Backtracking, Tree Traversal, Depth-First Search. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.