208. Implement Trie (Prefix Tree)
At a Glance
- Topic: Hash Table
- Pattern: Analyze Pattern
- Difficulty: Medium
- LeetCode: 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:
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.Example 1:
Input ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] Output [null, null, true, false, true, null, true]
Explanation Trie ...
Approach & Solution Steps
Use a TrieNode class with a map/array for children and a boolean flag isEndOfWord. Implement insert, search, and startsWith by walking down the children.
Optimal JS Solution
class TrieNode {
constructor() {
this.children = {};
this.isEnd = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let curr = this.root;
for (const char of word) {
if (!curr.children[char]) curr.children[char] = new TrieNode();
curr = curr.children[char];
}
curr.isEnd = true;
}
search(word) {
let curr = this.root;
for (const char of word) {
if (!curr.children[char]) return false;
curr = curr.children[char];
}
return curr.isEnd;
}
startsWith(prefix) {
let curr = this.root;
for (const char of prefix) {
if (!curr.children[char]) return false;
curr = curr.children[char];
}
return true;
}
}Edge Cases & Pitfalls
- Always consider empty or null inputs.
- Watch out for off-by-one index errors.
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?