Implement Trie (Prefix Tree)
Dynamic ProgrammingData Structures
MediumLeetCode #208
Problem Statement
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 with the following methods:
Trie()
- Initializes the trie objectinsert(word)
- Inserts the string word into the triesearch(word)
- Returns true if the string word is in the triestartsWith(prefix)
- Returns true if there is a previously inserted string that has the prefix
Example Trie Structure
Words inserted: apple, app, apricot, banana, band, bandana
Example queries:
- search("app") → true
- search("apple") → true
- search("appl") → false
- startsWith("app") → true
- startsWith("ban") → true
- startsWith("xyz") → false
Key Characteristics
- • Each node represents a single character
- • Root node is empty
- • Path from root to any node forms a prefix
- • End-of-word nodes are marked to distinguish complete words
- • Time complexity: O(m) for insert, search, and startsWith operations
- • Space complexity: O(ALPHABET_SIZE * N * M) where N is number of words and M is average length
Algorithm Explanation
A Trie (prefix tree) is a tree data structure that stores strings efficiently by sharing common prefixes. Each node represents a character, and paths from root to nodes form prefixes.
Key Operations
- Insert: Add a word by traversing/creating nodes for each character. Mark the final node as end-of-word.
- Search: Traverse the trie following the word's characters. Return true if we reach a node marked as end-of-word.
- StartsWith: Similar to search, but return true if we can traverse all prefix characters, regardless of end-of-word status.
Dynamic Programming Aspects
- Memoization: Each node stores the result of "does this prefix exist" to avoid recomputation.
- Optimal Substructure: Finding a word depends on finding its prefixes.
- Overlapping Subproblems: Multiple words share common prefixes, avoiding redundant storage.
Trie Insertion Demonstration
Inserting "cap" into a trie that already contains "cat" and "car"
Start: Initialize trie insertion
Starting insertion of "cap". Begin at root node.
Inserting word: "cap"
CAP
Step 1 of 5
Current Node
End of Word
Regular Node
Implement Trie (Prefix Tree) Solution