Trie Pattern: Template + 49 LeetCode Problems

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

  • 3 Easy
  • 24 Medium
  • 22 Hard
  • O(L) per insert or lookup, where L is the length of the word time

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.

Trie — Python 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.

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)

#ProblemDifficultyTopics
14Longest Common PrefixEasyTrie, Array, String
1065Index Pairs of a StringPremiumEasyTrie, Array, String +1
2932Maximum Strong Pair XOR IEasyBit Manipulation, Trie, Array +2

Medium (24)

#ProblemDifficultyTopics
139Word BreakMediumTrie, Memoization, Array +3
208Implement Trie (Prefix Tree)MediumDesign, Trie, Hash Table +1
211Design Add and Search Words Data StructureMediumDepth-First Search, Design, Trie +1
386Lexicographical NumbersMediumDepth-First Search, Trie
421Maximum XOR of Two Numbers in an ArrayMediumBit Manipulation, Trie, Array +1
648Replace WordsMediumTrie, Array, Hash Table +1
676Implement Magic DictionaryMediumDepth-First Search, Design, Trie +2
677Map Sum PairsMediumDesign, Trie, Hash Table +1
692Top K Frequent WordsMediumTrie, Array, Hash Table +5
720Longest Word in DictionaryMediumTrie, Array, Hash Table +2
1268Search Suggestions SystemMediumTrie, Array, String +3
616Add Bold Tag in StringPremiumMediumTrie, Array, Hash Table +2
758Bold Words in StringPremiumMediumTrie, Array, Hash Table +2
792Number of Matching SubsequencesMediumTrie, Array, Hash Table +4
820Short Encoding of WordsMediumTrie, Array, Hash Table +1
1023Camelcase MatchingMediumTrie, Array, Two Pointers +2
1166Design File SystemPremiumMediumDesign, Trie, Hash Table +1
1233Remove Sub-Folders from the FilesystemMediumDepth-First Search, Trie, Array +1
1698Number of Distinct Substrings in a StringPremiumMediumTrie, String, Suffix Array +2
1804Implement Trie II (Prefix Tree)PremiumMediumDesign, Trie, Hash Table +1
1858Longest Word With All PrefixesPremiumMediumDepth-First Search, Trie, Array +1
2261K Divisible Elements SubarraysMediumTrie, Array, Hash Table +3
2452Words Within Two Edits of DictionaryMediumTrie, Array, String
2707Extra Characters in a StringMediumTrie, Array, Hash Table +2

Hard (22)

#ProblemDifficultyTopics
140Word Break IIHardTrie, Memoization, Array +4
212Word Search IIHardTrie, Array, String +2
336Palindrome PairsHardTrie, Array, Hash Table +1
440K-th Smallest in Lexicographical OrderHardTrie
472Concatenated WordsHardDepth-First Search, Trie, Array +3
745Prefix and Suffix SearchHardDesign, Trie, Array +2
425Word SquaresPremiumHardTrie, Array, String +1
527Word AbbreviationPremiumHardGreedy, Trie, Array +2
588Design In-Memory File SystemPremiumHardDesign, Trie, Hash Table +2
642Design Search Autocomplete SystemPremiumHardDepth-First Search, Design, Trie +4
1032Stream of CharactersHardDesign, Trie, Array +2
1178Number of Valid Words for Each PuzzleHardBit Manipulation, Trie, Array +2
1316Distinct Echo SubstringsHardTrie, String, Hash Function +1
1707Maximum XOR With an Element From ArrayHardBit Manipulation, Trie, Array
1803Count Pairs With XOR in a RangeHardBit Manipulation, Trie, Array
1938Maximum Genetic Difference QueryHardBit Manipulation, Depth-First Search, Trie +2
1948Delete Duplicate Folders in SystemHardTrie, Array, Hash Table +2
2227Encrypt and Decrypt StringsHardDesign, Trie, Array +2
2416Sum of Prefix Scores of StringsHardTrie, Array, String +1
2479Maximum XOR of Two Non-Overlapping SubtreesPremiumHardTree, Depth-First Search, Graph +1
2935Maximum Strong Pair XOR IIHardBit Manipulation, Trie, Array +2
2977Minimum Cost to Convert String IIHardGraph, Trie, Array +3

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

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.

Meet the trie problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding 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 is saying — while staying invisible to screen sharing.