Code Snippets
/

Trie Implementation in JavaScript

Trie Implementation in JavaScript

A trie (prefix tree) supports insert, exact-match search, and prefix-search in O(L) where L is the word length, regardless of how many words are stored. This makes it the right structure for autocomplete, spell-check, and IP-routing tables. This snippet covers a Map-backed trie with insert and search, the startsWith prefix scan that powers autocomplete, and a wordsWithPrefix collector that returns every match.

JavaScript
Medium
3 snippets
data-structures
trie
code-template
strings

769 views

14

class Trie {
    constructor() {
        this.root = { children: new Map(), end: false };
    }
    insert(word) {
        let node = this.root;
        for (const ch of word) {
            if (!node.children.has(ch)) node.children.set(ch, { children: new Map(), end: false });
            node = node.children.get(ch);
        }
        node.end = true;
    }
    search(word) {
        let node = this.root;
        for (const ch of word) {
            if (!node.children.has(ch)) return false;
            node = node.children.get(ch);
        }
        return node.end;
    }
}

const t = new Trie();
for (const w of ['cat', 'car', 'cart']) t.insert(w);
console.log(t.search('cat'));  // true
console.log(t.search('ca'));   // false (prefix, not full word)
console.log(t.search('cars')); // false

Each trie node stores a Map of next-character pointers and a boolean end flag marking whether a word terminates there. Insert walks the chain creating nodes as needed, then sets end = true at the last character. Search walks the same chain and returns node.end, which is what distinguishes 'this is a stored word' from 'this is just a prefix'. The Map (not a plain object) keeps the API clean for unicode keys and avoids prototype-pollution gotchas. Time complexity is O(L) per operation, space is O(N * L) total for N words.