Skip to content
DSA in JavaScript
← All patterns

Trie / Prefix Search

0/10 solved

What it is

A tree where each edge is one character, so every word sharing a prefix shares a path. Looking up a prefix costs only the length of the prefix.

Used for

Autocomplete, spell check, prefix search, word search on a board.
·catr

Step 1 of 5

Goal: store many words so we can quickly ask "does any word start with these letters?" A trie is a tree where each step down is one letter, so words that share a beginning share a path. Add "cat", starting from an empty root.

You see

  • Prefix lookup or autocomplete
  • Many words searched on a grid
  • Longest common prefix

Learn it in

Trie

Template

class Trie {  root = {};  insert(w) { let n = this.root; for (const c of w) n = n[c] ??= {}; n.end = true; }  startsWith(p) { let n = this.root; for (const c of p) if (!(n = n[c])) return false; return true; }}

Practice problems