The Implement Trie (Prefix Tree) interview question is one of the most fundamental data structure design tasks. You need to implement a "Prefix Tree" or "Trie" that supports three operations:
insert(word): Adds a word to the tree.search(word): Returns true if the exact word exists.startsWith(prefix): Returns true if any word in the Trie starts with the given prefix.Tries are ubiquitous in search engines, IP routing, and auto-complete systems. This question is a favorite at Google, Meta, and Amazon because it tests whether you understand how to share prefixes to save space and speed up searches. It also evaluates your skill in designing custom recursive structures and choosing between a Map or a fixed-size array for child pointers.
The problem uses the Trie design pattern.
isEndOfWord.isEndOfWord = true.isEndOfWord is true.isEndOfWord flag at the end.root -> c -> a -> r (end).root -> c -> a -> t (end). (The "ca" prefix is shared).c -> a. Ends at 'a', but isEndOfWord is false. Returns false.c -> a. Path exists. Returns true.search).Be ready to discuss Space Complexity. A Trie can consume a lot of memory because of the null pointers. Interviewers may ask how to optimize this (e.g., using a Hash Map for children instead of an array, or using a "Ternary Search Tree").
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Design File System | Medium | Solve | |
| Implement Trie II (Prefix Tree) | Medium | Solve | |
| Map Sum Pairs | Medium | Solve | |
| Implement Magic Dictionary | Medium | Solve | |
| Design In-Memory File System | Hard | Solve |