Typorithm · medium

Trie Insert

trie-inserttriesprefix-treemap-childrenbuild
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Trie Insert

0%

Tries

A trie stores words by character path; insert walks the word, creating child nodes and marking the last as a word end.

A trie (prefix tree) shares common prefixes across words, so each edge is one character.

Each node holds a Map from character to child and a flag for whether a word ends there.

Insertion walks the word, creating any missing children, and flags the final node as a word terminal.

01

Children stored in a Map per node.

02

Create child nodes on demand.

03

Mark the last node isEnd = true.

class Trie {
  constructor() {
    this.children = new Map();
    this.isEnd = false;
  }

  insert(word) {
    let node = this;
    for (const ch of word) {
      if (!node.children.has(ch)) {
        node.children.set(ch, new Trie());
      }
      node = node.children.get(ch);
    }
    node.isEnd = true;
  }
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Children map

Each node maps a character to its child node.

this.children = new Map()

2. Word terminal

A flag marks where a complete word ends.

this.isEnd = false

3. Create missing edge

Add a child node when the character path is missing.

node.children.set(ch, new Trie())

4. Walk down

Move into the child for the next character.

node = node.children.get(ch)

5. Mark end

The final node marks a stored word.

node.isEnd = true

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Trie Insert: Lesson & Practice · Typorithm | ApplyDjinn