JavaScript Snippet

Trie Implementation in JavaScript

Difficulty: Medium

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.

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

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.