Implement Trie (Prefix Tree) - Problem

A trie (pronounced as "try") or prefix tree is a specialized tree data structure that efficiently stores and retrieves strings. Think of it as a digital dictionary where each path from root to node represents a sequence of characters.

Tries are incredibly useful for applications like:

  • Autocomplete systems (like Google search suggestions)
  • Spell checkers (finding words with common prefixes)
  • IP routing (longest prefix matching)
  • T9 predictive text

Your task is to implement a Trie class with these core operations:

  • Trie() - Initialize an empty trie
  • insert(word) - Add a word to the trie
  • search(word) - Check if a complete word exists
  • startsWith(prefix) - Check if any word starts with the given prefix

Example: After inserting "cat", "cats", and "dog", searching for "cat" returns true, but searching for "ca" returns false. However, startsWith("ca") returns true because "cat" and "cats" start with "ca".

Input & Output

basic_operations.py โ€” Python
$ Input: trie = Trie() trie.insert("apple") trie.search("apple") # True trie.search("app") # False trie.startsWith("app") # True trie.insert("app") trie.search("app") # True
โ€บ Output: True False True True
๐Ÿ’ก Note: After inserting "apple", searching for the complete word returns True, but "app" returns False since it wasn't inserted as a complete word. However, startsWith("app") returns True because "apple" starts with "app". After inserting "app", searching for "app" now returns True.
multiple_words.py โ€” Python
$ Input: trie = Trie() trie.insert("car") trie.insert("card") trie.insert("care") trie.insert("careful") trie.search("car") # True trie.search("card") # True trie.startsWith("care") # True trie.search("caring") # False
โ€บ Output: True True True False
๐Ÿ’ก Note: Multiple words with common prefixes are efficiently stored. All inserted words can be found, prefixes match appropriately, but words that weren't inserted (like "caring") return False even if they share prefixes with inserted words.
edge_cases.py โ€” Python
$ Input: trie = Trie() trie.search("") # False (empty not inserted) trie.startsWith("") # True (empty prefix matches all) trie.insert("") trie.search("") # True (now empty is inserted) trie.insert("a") trie.startsWith("ab") # False (no words start with "ab")
โ€บ Output: False True True False
๐Ÿ’ก Note: Edge case handling: empty string as word vs. prefix, and checking prefixes that don't exist in the trie. Empty prefix technically matches all words (including none), but empty word needs to be explicitly inserted to be found.

Visualization

Tap to expand
Trie Construction: cat, cats, carROOTccaatt"cat"ss"cats"rr"car"๐ŸŽฏ Key Insight: Common prefixes ("ca") are shared, saving space and enabling fast lookups
Understanding the Visualization
1
Empty Trie
Start with just the root node
2
Insert "cat"
Create path: root โ†’ c โ†’ a โ†’ t (mark as word end)
3
Insert "cats"
Reuse existing "cat" path, add 's' and mark end
4
Insert "car"
Reuse 'c' โ†’ 'a', branch to 'r' and mark end
5
Search "cat"
Follow path and verify end marker exists
Key Takeaway
๐ŸŽฏ Key Insight: Tries excel at storing strings with common prefixes by sharing nodes for identical character sequences, making them perfect for autocomplete, spell checkers, and dictionary applications.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(m)

Where m is the length of the word/prefix. Each operation traverses at most m nodes in the tree.

n
2n
โœ“ Linear Growth
Space Complexity
O(ALPHABET_SIZE * N * M)

In worst case, where N is number of words, M is average length, and ALPHABET_SIZE is typically 26 for lowercase letters. Common prefixes are shared.

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค word.length, prefix.length โ‰ค 2000
  • word and prefix consist of only lowercase English letters
  • At most 3 ร— 104 calls will be made to insert, search, and startsWith
  • All input strings are non-empty for insert and search operations
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28 Apple 22
425.0K Views
High Frequency
~25 min Avg. Time
8.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen