Skip to content
DSA Patterns
Menu
Language
TrieLC #2081 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Mediumtrie

Implement Trie (Prefix Tree)

Problem (restated)

Implement Trie with insert, search (full word), and startsWith (prefix).

Intuition

Children map/array per node; end-of-word flag.

Approaches

Trie insert/search/startsWith

Unverified
Time O(L) per opSpace O(Σ L)

Idea. walk edges per char; create on insert; search needs end flag.

Walkthrough. insert apple; search apple true; search app false; startsWith app true.

Trade-offs. Array[26] fastest for lowercase; map generalizes.

Solution
class TrieNode {
  children: Map<string, TrieNode> = new Map();
  end = false;
}

export class Trie {
  private root = new TrieNode();
  insert(word: string): void {
    let n = this.root;
    for (const c of word) {
      if (!n.children.has(c)) n.children.set(c, new TrieNode());
      n = n.children.get(c)!;
    }
    n.end = true;
  }
  search(word: string): boolean {
    const n = this.walk(word);
    return !!n && n.end;
  }
  startsWith(prefix: string): boolean {
    return !!this.walk(prefix);
  }
  private walk(s: string): TrieNode | null {
    let n = this.root;
    for (const c of s) {
      if (!n.children.has(c)) return null;
      n = n.children.get(c)!;
    }
    return n;
  }
}
class TrieNode {
  children: Map<string, TrieNode> = new Map();
  end = false;
}

export class Trie {
  private root = new TrieNode();
  insert(word: string): void {
    let n = this.root;
    for (const c of word) {
      if (!n.children.has(c)) n.children.set(c, new TrieNode());
      n = n.children.get(c)!;
    }
    n.end = true;
  }
  search(word: string): boolean {
    const n = this.walk(word);
    return !!n && n.end;
  }
  startsWith(prefix: string): boolean {
    return !!this.walk(prefix);
  }
  private walk(s: string): TrieNode | null {
    let n = this.root;
    for (const c of s) {
      if (!n.children.has(c)) return null;
      n = n.children.get(c)!;
    }
    return n;
  }
}

Template connection

A map of children per node. insert creates the missing edge for each character and marks the last node. search requires that mark. startsWith returns once the walk stays on the trie.

Reflection

  • search needs the end-of-word flag. startsWith only needs the walk not to break.
  • A missing letter is absent. The empty word is the root’s flag. Inserting the same word twice still counts once.
  • One child per letter. A length-26 array fits a dense alphabet. A map fits a sparse one.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 7
1/7

Empty trie. Insert apple, then search apple / app and startsWith app.

.

children map · isWord flag

Key:CurrentActive rangeMatchSettled