Trie
Expert Answer & Key Takeaways
Trie: The Prefix Powerhouse
1. Core Operations & Complexity
| Operation | Description | Time Complexity | Space Complexity |
|---|---|---|---|
Insert(word) | Add a word to the trie. | worst case | |
Search(word) | Check if a word exists in the trie. | ||
StartsWith(pre) | Check if any word starts with prefix pre. |
2. Why Use a Trie Over a Hash Map?
- Prefix Searching: Tries can find all keys with a common prefix in time ( is the number of matches).
- Ordered Traversal: Keys can be retrieved in alphabetical order easily.
- Space Efficiency: Tries can save space when many keys share long common prefixes.
- No Hash Collisions: Tries avoid the overhead and worst-case scenarios of hash tables.
3. Implementation Patterns
Array vs. HashMap for Children
- Array
[26]: Fastest access ( to find child), but space-intensive if the alphabet is large or the trie is sparse. - HashMap: More space-efficient for sparse trees or large character sets (e.g., Unicode), but slightly slower due to hashing overhead.
4. Key Signals in Interviews:
- Autocomplete/Typeahead: Suggesting words as the user types.
- Longest Common Prefix: Finding the shared beginning of multiple strings.
- Wildcard Matching: Searching for words with missing characters (e.g.,
s.r). - Bitwise XOR: Binary Tries (storing bits) are used to find maximum XOR pairs in per query.
Implement Trie (Prefix Tree)
insert, search, and startsWith operations.Examples
Level I: HashMap-based Trie
Intuition
Detailed Dry Run
Level III: Array-based Trie (Optimal)
Intuition
[26] for lowercase English. Fastest possible access with minimal memory overhead for dense tries.Detailed Dry Run
Add and Search Word
Examples
Level III: Trie + DFS (Optimal)
Intuition
Detailed Dry Run
Map Sum Pairs
Level III: Trie with Pre-calculated Sums (Optimal)
Intuition
Detailed Dry Run
Replace Words
Examples
Level I: HashSet of Roots
Intuition
Detailed Dry Run
Level III: Trie (Optimal)
Intuition
isEndOfWord node encountered provides the shortest root.Detailed Dry Run
Word Search II
The Challenge of Multiple Words
Trie for Prefix Sharing
Optimization: Trie Pruning
m x n board of characters and a list of strings words, return all words on the board.Examples
Level I: Naive DFS (Multiple Word searches)
Intuition
word in words, scan every cell (r, c). If board[r][c] == word[0], start a DFS to find the rest of the characters.Detailed Dry Run
Level II: Backtracking with Trie
Intuition
node.isEndOfWord, add the word to result.Detailed Dry Run
Level III: Optimized Trie (Node Removal)
Intuition
word is extracted, if it has no children, we can delete the node from its parent to avoid re-visiting dead branches.parent pointer or count to each node. When word != "", set it to null. If children count becomes 0, remove the entry from search path completely.Detailed Dry Run
Design Search Autocomplete System
Visual Representation
Typed: "i"
Prefix "i" matches "i love you" (5), "island" (3), "ironman" (2).
Return: ["i love you", "island", "ironman"]
Typed: " " (space)
Prefix "i " matches "i love you" (5), "i a cool" (2).
Return: ["i love you", "i a cool"]Examples
Level I: HashMap (Brute Force Prefix Search)
Intuition
Level III: Trie + Top-3 Cache
Intuition
Word Squares
words, return all the word squares you can build from words. The same word from words can be used multiple times. A sequence of words forms a valid word square if the kth row and kth column read the exact same string for each 0 <= k < max(numRows, numColumns).Examples
Level I: Brute Force Backtracking
Intuition
Level III: Trie + Backtracking
Intuition
k, we need to find words that start with a specific prefix. This prefix is formed by the characters at position k of the words already chosen. A Trie is the perfect data structure to quickly fetch all words sharing a common prefix.Maximum XOR of Two Numbers in an Array
nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.Visual Representation
Nums: [3, 10, 5, 25, 2, 8]
Max XOR: 5 XOR 25 = 28
Binary Trie approach:
1. Insert all numbers as 32-bit binary strings into a Trie.
2. For each number X, find a path that maximizes XOR.
3. To maximize XOR, at each bit, try to go to the opposite bit (if curr is 0, try 1).
If opposite exists, result |= (1 << bit).Examples
Level I: Brute Force
Intuition
Level III: Binary Trie
Intuition
Camelcase Matching
pattern if we can insert lowercase letters to the pattern so that it equals the query. Return a list of booleans.Visual Representation
Queries: ["FooBar", "FooBarTest", "FootBall"]
Pattern: "FB"
"FooBar" -> F-oo-B-ar -> Matches!
"FooBarTest" -> F-oo-B-ar-T-est -> Extra 'T' (Uppercase) -> Fails!Examples
Level I: Two Pointers (Standard Search)
Intuition
pattern is a subsequence. Additionally, ensure that any uppercase letters in the word that are NOT in the pattern cause a mismatch.Level III: Two Pointers / Trie
Intuition
Prefix and Suffix Search
Visual Representation
Words: ["apple"]
Suffix#Prefix construction: "e#apple", "le#apple", "ple#apple", ...
Insert these into a Trie.
Query: prefix="ap", suffix="le"
Search Trie for "le#ap".
Found node stores max index: 0.Examples
Level I: HashMap (All Combinations)
Intuition
prefix + '#' + suffix combinations for every word and store them in a HashMap with their index. Query is O(1). Inefficient space but simple.Level III: Wrapped Trie ({suffix}#{prefix})
Intuition
Word Ladder II
beginWord and endWord, and a dictionary wordList, return all shortest transformation sequences from beginWord to endWord. Only one letter can be changed at a time.Examples
Level I: Standard BFS (Shortest Transformation)
Intuition
beginWord to endWord. In each step, change one character at a time and check if it exists in the dictionary. This approach only finds the length of the shortest path, not the actual paths themselves.Level III: BFS + Backtracking (Trie for Neighbors)
Intuition
beginWord to all reachable words. To quickly find 'neighbors' (words differing by one char), we can iterate through each position of the word and try all 26 letters, checking against a Set/Trie. Finally, use DFS to backtrack all shortest paths from beginWord to endWord using the distance levels found in BFS.Concatenated Words
words (without duplicates), return all the concatenated words in the given list of words. A concatenated word is defined as a string that is entirely comprised of at least two shorter words in the given array.Visual Representation
Words: ["cat", "dog", "catdog"]
DFS(0):
1. Prefixes found: "cat" (Trie matches).
2. Remaining: "dog".
3. DFS("dog"): Prefix found: "dog". Remaining: "".
4. SUCCESS -> "catdog" is concatenated.Examples
Level I: Set-based DFS
Intuition
Level III: Trie + DFS + Memoization
Intuition
Palindrome Pairs
(i, j) such that the concatenation of the two words words[i] + words[j] is a palindrome.Visual Representation
Words: ["abcd", "dcba", "lls", "s", "sssll"]
Pairs:
1. "abcd" + "dcba" = "abcddcba" (Palindrome)
2. "dcba" + "abcd" = "dcbaabcd" (Palindrome)
3. "s" + "lls" = "slls" (Palindrome)
4. "sssll" + "lls" = "ssslllls" (Wait, no...)
Wait: "lls" + "s" = "llss" (No)
Actual: "sssll" + "lls" -> "ssslllls" NO.
Let's check "lls" reverse is "sll".
If we pick i="sssll", j="lls", words[i]+words[j] = "ssslllls" Fails.
Correct for "lls": s + lls = slls (Correct).Examples
Level I: Brute Force (Check all pairs)
Intuition
words[i] + words[j] and check if it is a palindrome. This is , which is too slow for large inputs.Level III: Trie (Suffix-to-Prefix matching)
Intuition
Shortest Unique Prefix
Visual Representation
Words: ["zebra", "dog", "duck", "dove"]
Trie with counts:
root
-> z(1) -> e(1) ... -> found count=1 at 'z'
-> d(3)
-> o(2)
-> g(1) -> found count=1 at 'g' (prefix "dog")
-> v(1) -> found count=1 at 'v' (prefix "dov")
-> u(1) -> found count=1 at 'u' (prefix "du")Examples
Level I: Brute Force Comparison
Intuition
Level III: Trie (Node Visited Count)
Intuition
count) for each node along the path. To find the shortest unique prefix for a word, traverse the Trie until you reach a node with count == 1. That node marks the end of the shortest unique prefix.Maximum XOR with an Element from Array
nums, return the maximum value of nums[j] XOR xi where nums[j] <= mi. If all numbers in nums are larger than mi, the answer is -1.Visual Representation
Nums: [0, 1, 2, 3, 4]
Query: [3, 1] (x=3, m=1)
Valid nums <= 1: [0, 1]
XOR results: 3^0=3, 3^1=2
Max: 3
Optimal approach:
1. Sort nums.
2. Sort queries by m.
3. Insert nums into Trie as long as nums[j] <= m.
4. Query Trie for max XOR.Examples
Level I: Brute Force
Intuition
[xi, mi], iterate through every number in the nums array. If nums[j] <= mi, calculate nums[j] XOR xi and update the maximum. Simple O(N*Q) solution.Level III: Offline Queries + Binary Trie
Intuition
Word Break II
s and a string dictionary wordDict, return all possible sentences that can be formed by adding spaces to s such that each word is a valid dictionary word.Visual Representation
s = "catsanddog", dict = ["cat","cats","and","sand","dog"]
Trie path 1: root -> c -> a -> t -> s (word) -> a -> n -> d (word) -> d -> o -> g (word)
Trie path 2: root -> c -> a -> t (word) -> s -> a -> n -> d (word) -> d -> o -> g (word)
Sentences:
1. "cats and dog"
2. "cat sand dog"Examples
Level I: Standard Recursion
Intuition
Level III: Trie + DFS + Memoization
Intuition
Boggle Game
Visual Representation
Board: ["abc", "def", "ghi"]
Words: ["abc", "defi", "gh"]
Possible Selections:
1. {"abc", "def"} -> 2 words
2. {"abc"} -> 1 word
Result: 2Examples
Level I: Brute Force DFS
Intuition
Level III: Trie + Backtracking (Max Independent Sets)
Intuition
Stream of Characters
Examples
Level I: Brute Force Suffix Comparison
Intuition
Level III: Reverse Trie
Intuition
Longest Word in Dictionary through Deleting
s and a string dictionary dictionary, return the longest string in the dictionary that can be formed by deleting some characters of the given string s.Examples
Level I: Two Pointers (Standard Search)
Intuition
s. Keep track of the longest word found (using lexicographical order for ties).Level III: Trie (Index-based Subsequence Search)
Intuition
s in a way that allows fast subsequence checks. For each character a-z, store a list of indices where it appears in s. For any word, use binary search to find the smallest valid index for the next character. A Trie of words can also be used to explore multiple words simultaneously.Prefix and Suffix Search (Optimized Query)
Level I: Brute Force Search
Intuition
prefix and ends with the suffix. Return the maximum index found. O(N * L) per query.Level III: Precomputed HashMap of Pairs
Intuition
prefix + " " + suffix as the key and the max index as the value.Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.