✨ What is a Trie?
A Trie (pronounced like "try") is a special type of tree used to store strings, particularly useful for prefix-based lookups. Unlike typical trees, each node in a Trie represents a single character, and paths down the tree represent strings.
Think of it like an autocomplete brain — super efficient at saying:
"Do any words start with 'hel'?" or "Does this word exist exactly?"
✅ Why Use a Trie?
- 🔍 Fast word search
- 📜 Efficient prefix matching (perfect for autocomplete!)
- ⚡ Can handle thousands of strings efficiently
- 🧠 Great for dictionary-like problems
🧩 Our JavaScript Implementation
We’ll use a simple object-based structure (instead of a class-based node) to keep it lightweight and readable.
🔧 Trie Structure
var Trie = function () {
this.root = {};
};
-
this.root
is the base of our Trie. - Each key in the nested objects is a letter.
- At the end of a complete word, we mark it with
isEnd = true
.
✍️ Insert Method
Trie.prototype.insert = function (word) {
let node = this.root;
for (let letter of word) {
if (!node[letter]) {
node[letter] = {};
}
node = node[letter];
}
node.isEnd = true;
};
- Traverse character by character.
- Create nodes as needed.
- Mark the end of a word with
isEnd = true
.
🔎 Search Method
Trie.prototype.search = function (word) {
let node = this.root;
for (let letter of word) {
if (!node[letter]) return false;
node = node[letter];
}
return node.isEnd === true;
};
- Traverse the word.
- Return
true
only if it exists and ends as a complete word.
🔍 Prefix Check (startsWith
)
Trie.prototype.startsWith = function (prefix) {
let node = this.root;
for (let letter of prefix) {
if (!node[letter]) return false;
node = node[letter];
}
return true;
};
- Just checks if the prefix exists.
- Doesn't care if it's a complete word.
🧠 Time & Space Complexity
Operation | Time Complexity | Space Complexity |
---|---|---|
Insert | O(n) | O(n) |
Search | O(n) | O(1) |
startsWith | O(n) | O(1) |
Where
n
is the length of the word or prefix.
Why so fast?
- No sorting
- No hashing
- Direct tree traversal: O(1) access per character
🌍 Real-World Applications
Here’s where Tries shine like a boss:
🔤 Autocomplete / Search Suggestions
e.g. Google, IDEs, chat apps📚 Spell Checkers
Efficient lookup of valid words🔐 IP Routing (Longest Prefix Matching)
Used in networking to match IP addresses🎮 Word Games
Like Scrabble, Boggle — finding all valid words from a set of characters💬 Text Prediction
For keyboards and messaging apps🕵️ Detecting Bad Words
Check for banned terms in chat, URLs, or usernames
🧪 Example in Action
const trie = new Trie();
trie.insert("cat");
trie.insert("car");
console.log(trie.search("cat")); // true
console.log(trie.search("ca")); // false
console.log(trie.startsWith("ca")); // true
console.log(trie.startsWith("bat")); // false
🧯 Limitations & Enhancements
This basic Trie works well but can be enhanced with:
- ✅ Word frequency counters (for top suggestions)
- 🔁 Word deletion
- 🤖 Autocomplete engine (based on prefix)
- 🌳 Use a TrieNode class for more structure and features
🚀 Final Thoughts
Tries are super powerful data structures that often get overlooked in favor of HashMaps or Arrays. But for problems involving prefixes, string searches, and dictionary operations, they're hard to beat.
Whether you're building a search feature, a chatbot, or a predictive keyboard — Trie is your friend.
Top comments (0)