Implement Trie (Prefix Tree)
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: 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.
Constraints:
- 1 <= word.length, prefix.length <= 2000
- word and prefix consist only of lowercase English letters.
- At most 3 * 10^4 calls in total will be made to insert, search, and startsWith.
Input Format:
- Commands to execute operations on Trie data structure.
Output Format:
- Results of operations performed on the Trie data structure.
Examples:
Example 1:
Input:
Input ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output:
Output [null, null, true, false, true, null, true]
Explanation:
Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // return True trie.search("app"); // return False trie.startsWith("app"); // return True trie.insert("app"); trie.search("app"); // return True
Solutions
Standard Trie Implementation with Array
Implement a trie using an array of 26 child nodes for each trie node, where each position in the array corresponds to a lowercase letter.
HashMap Implementation
Implement a trie using a HashMap for each node's children instead of an array. This approach is more flexible for different character sets but may have slightly more overhead.
Algorithm Walkthrough
Example input: nums = []
Step-by-step execution:
- Initialize a new Trie with an empty root node
- Insert "apple":
- Create nodes for 'a', 'p', 'p', 'l', 'e'
- Mark the node for 'e' as the end of a word
- Search for "apple":
- Follow path 'a' -> 'p' -> 'p' -> 'l' -> 'e'
- The node at 'e' is marked as the end of a word
- Return true
- Search for "app":
- Follow path 'a' -> 'p' -> 'p'
- The node at 'p' is not marked as the end of a word
- Return false
- StartsWith "app":
- Follow path 'a' -> 'p' -> 'p'
- The prefix path exists
- Return true
- Insert "app":
- Follow existing path 'a' -> 'p' -> 'p'
- Mark the node at 'p' as the end of a word
- Search for "app":
- Follow path 'a' -> 'p' -> 'p'
- The node at 'p' is now marked as the end of a word
- Return true
Hints
Hint 1
Hint 2
Hint 3
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize the trie data structure and how words are stored and searched in it.
Key visualization elements:
- current node
- inserted word path
- search path
- matching prefix
Similar Questions
Design Add and Search Words Data Structure
MediumDesign a data structure that supports adding new words and finding if a string matches any previously added string. Implement the WordDictionary class: WordDictionary() Initializes the object. void addWord(word) Adds word to the data structure, it can be matched later. bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.
Word Search II
HardGiven an m x n board of characters and a list of strings words, return all words on the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Implementation Notes
Tries are fundamental data structures for fast prefix lookups. They're commonly used in applications like autocomplete, spell checking, and IP routing.