Trie Prefix Search
Trie Prefix Search
Implement a Trie (prefix tree) that supports inserting words and searching by full word or prefix.
Operations:
Insert(word)— store the word in the trieSearch(word)— return true if the word existsStartsWith(prefix)— return true if any word starts with the prefix
Function signature
type Trie struct { /* ... */ }
func NewTrie() *Trie
func (t *Trie) Insert(word string)
func (t *Trie) Search(word string) bool
func (t *Trie) StartsWith(prefix string) bool
Examples
Example 1:
Insert("apple")
Search("apple") -> true
Search("app") -> false
StartsWith("app") -> true
Insert("app")
Search("app") -> true
Constraints
- 1 <= word.length, prefix.length <= 30
- Words consist of lowercase letters a-z
- Up to 10^5 operations
Hints
- Each node holds a map of children and an
isWordflag. - Insert walks the trie, creating nodes as needed.
- Search and StartsWith differ only at the end check.
Notes
- Trie is great for fast prefix queries and autocomplete.
- Memory usage is higher than hash sets but structured by prefixes.
Run tests to see results
No issues detected