Implement Trie (Prefix Tree) - Problem

A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

  • Trie() Initializes the trie object.
  • void insert(String word) Inserts the string word into the trie.
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

Input & Output

Example 1 — Basic Trie Operations
$ Input: operations = ["Trie", "insert", "search", "search", "startsWith", "insert", "search"], values = ["", "apple", "apple", "app", "app", "app", "app"]
Output: [null, null, true, false, true, null, true]
💡 Note: Create trie, insert "apple", search "apple" (found), search "app" (not found), check prefix "app" (exists), insert "app", search "app" (now found)
Example 2 — Multiple Words with Shared Prefix
$ Input: operations = ["Trie", "insert", "insert", "search", "startsWith"], values = ["", "car", "card", "care", "car"]
Output: [null, null, null, false, true]
💡 Note: Insert "car" and "card", search "care" (not found), but "car" is a valid prefix
Example 3 — Single Character Operations
$ Input: operations = ["Trie", "insert", "search", "startsWith"], values = ["", "a", "a", "a"]
Output: [null, null, true, true]
💡 Note: Edge case with single character: insert "a", search "a" (found), "a" starts with "a"

Constraints

  • 1 ≤ word.length, prefix.length ≤ 2000
  • word and prefix consist only of lowercase English letters
  • At most 3 × 104 calls in total will be made to insert, search, and startsWith

Visualization

Tap to expand
Trie Operations: Insert → Search → Prefix CheckOperations["Trie", "insert", "search"]["", "apple", "apple"]rootap...e1. insert("apple")→ Create path a-p-p-l-e2. search("apple")→ Follow path, check end markerOutput[null, null, true]
Understanding the Visualization
1
Input
Series of operations: insert, search, startsWith with word values
2
Process
Build tree structure sharing common prefixes between words
3
Output
Array of results: null for insert, boolean for search/startsWith
Key Takeaway
🎯 Key Insight: A trie shares common prefixes in a tree structure, making prefix operations extremely efficient
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 25
339.8K Views
High Frequency
~25 min Avg. Time
8.9K 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