AlgoTales · Roadmap

Insert

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Inserting into a trie means following a word letter by letter, building any missing branch, and putting a flag on the last letter. It is how you load a dictionary, contact list or rule table into the structure so searches later are fast.

Practical use cases

  • Web app: Loading products into the search index. When your shop app starts, or when an admin adds a new product "Redmi Note 13", the name is inserted letter by letter into the suggestion trie. Only the letters that are new create new branches. So adding one product never rebuilds the whole index and the new item appears in suggestions at once.
  • Web app: Adding a new contact on the fly. In a contacts app, saving "Ananya" makes the code walk A, N, A, N, Y, A, reuse the branch shared with "Anand" and "Anil", and add only the missing pieces. Because shared starts are not duplicated, even a hundred thousand contacts stay small enough to keep in the browser. Staff can add a contact during a call and see it appear in suggestions a moment later.
  • System: Router tables and IDE suggestions. Routers add a new address rule and code editors add a new function name into their prefix trees as you type. Each addition touches only a few nodes, so the tools stay responsive. This is why such tools can accept new entries all day without ever pausing to rebuild their whole lookup table.

The story: The Wedding Name-Board

Zoya's cousin was getting married, and the hall had a huge name-board at the gate so guests could find their table. Every relative was written by hand, one word at a time, on separate strips. By evening the board looked like a shelf of long ribbons, and Zoya had written "Sharma" and "Sharad" with the same five letters twice.

"Stop!" said Mrs. Sharma, who happened to be a guest and a teacher. "When a new guest arrives, first see how much of the name is already on the board. Follow it letter by letter. Where the board runs out, add only the missing letters."

Zoya tried it for "Sharada". She walked S-H-A-R-A (all there), then found nothing for D... so she wrote the last two letters under it and put a tiny green flag after A. No ribbon was copied; the board grew by exactly what was new.

That is trie insertion: walk the word letter by letter, reuse a box if it exists, create it if not, and finally mark the last box as "a word ends here".

How to spot this problem, and where you need it

You need to keep a fast-searchable set of words that keeps changing as users add new names, products or rules, without rebuilding everything each time.

Signs you need it

  • New words arrive all the time (new products, users, tags) and the suggestion list must include them immediately.
  • You currently re-sort or rebuild the whole list after every new entry.
  • Many of the words begin with the same letters, so storing each one fully wastes memory.
  • The problem says "implement a dictionary with add word" or "build a prefix tree".

Where to use it in a project

  • The startup code that loads products, cities or usernames into an in-memory search helper.
  • The "save" handler of an admin form that should update suggestions right away.

The solution

Start at the root. For each letter of the word, check whether the current node already has a child for that letter. If it does, step into it; if not, create it first and step in. After the last letter, mark that node as the end of a word. Repeated starts are naturally shared, and the work is just the length of the word.

Payoff: Before: rebuilding or re-sorting 100,000 words for every new one. After: about 10 small steps per word added.

Explain it like I am 8

To add a word, start at the door and follow its letters. If a room for the next letter exists, walk in. If not, build the room first. At the very last letter, hang a green flag so everybody knows the word stops there.

How it works, step by step

  1. Stand at the root.
  2. For each letter of the word, check if the current node has a child for that letter.
  3. If the child is missing, create it. Then move to that child.
  4. After the last letter, set the node's end flag to true.
  5. Inserting an existing word changes nothing except possibly setting the flag (it is safe to repeat).

The code in four languages

PHP

<?php
class TrieNode {
    public array $kids = [];      // letter => TrieNode
    public bool $end = false;     // true if a word stops here
}

class Trie {
    public TrieNode $root;
    public function __construct() { $this->root = new TrieNode(); }

    // Returns how many NEW boxes were created.
    public function insert(string $word): int {
        $node = $this->root;
        $created = 0;
        foreach (str_split($word) as $ch) {
            if (!isset($node->kids[$ch])) {
                $node->kids[$ch] = new TrieNode();   // missing: build it
                $created++;
            }
            $node = $node->kids[$ch];                // step down
        }
        $node->end = true;                           // green flag
        return $created;
    }
}

$t = new Trie();
foreach (['cat', 'car', 'cub', 'do', 'dog', 'cat'] as $w) {
    echo $w . ': ' . $t->insert($w) . ' new boxes' . PHP_EOL;
}

JavaScript

class TrieNode {
  constructor() {
    this.kids = {};      // letter -> TrieNode
    this.end = false;    // true if a word stops here
  }
}

class Trie {
  constructor() { this.root = new TrieNode(); }

  // Returns how many NEW boxes were created.
  insert(word) {
    let node = this.root;
    let created = 0;
    for (const ch of word) {
      if (!node.kids[ch]) {
        node.kids[ch] = new TrieNode();   // missing: build it
        created++;
      }
      node = node.kids[ch];               // step down
    }
    node.end = true;                      // green flag
    return created;
  }
}

const t = new Trie();
for (const w of ['cat', 'car', 'cub', 'do', 'dog', 'cat']) {
  console.log(w + ': ' + t.insert(w) + ' new boxes');
}

Java

import java.util.*;

public class Main {
    static class TrieNode {
        Map<Character, TrieNode> kids = new HashMap<>();   // letter -> TrieNode
        boolean end = false;                               // true if a word stops here
    }

    static class Trie {
        TrieNode root = new TrieNode();

        // Returns how many NEW boxes were created.
        int insert(String word) {
            TrieNode node = root;
            int created = 0;
            for (char ch : word.toCharArray()) {
                if (!node.kids.containsKey(ch)) {
                    node.kids.put(ch, new TrieNode());     // missing: build it
                    created++;
                }
                node = node.kids.get(ch);                  // step down
            }
            node.end = true;                               // green flag
            return created;
        }
    }

    public static void main(String[] args) {
        Trie t = new Trie();
        for (String w : new String[]{"cat", "car", "cub", "do", "dog", "cat"}) {
            System.out.println(w + ": " + t.insert(w) + " new boxes");
        }
    }
}

Go

package main

import "fmt"

type TrieNode struct {
	kids map[rune]*TrieNode // letter -> TrieNode
	end  bool               // true if a word stops here
}

func newTrieNode() *TrieNode { return &TrieNode{kids: map[rune]*TrieNode{}} }

type Trie struct {
	root *TrieNode
}

func NewTrie() *Trie { return &Trie{root: newTrieNode()} }

// Insert returns how many NEW boxes were created.
func (t *Trie) Insert(word string) int {
	node := t.root
	created := 0
	for _, ch := range word {
		if node.kids[ch] == nil {
			node.kids[ch] = newTrieNode() // missing: build it
			created++
		}
		node = node.kids[ch] // step down
	}
	node.end = true // green flag
	return created
}

func main() {
	t := NewTrie()
	for _, w := range []string{"cat", "car", "cub", "do", "dog", "cat"} {
		fmt.Printf("%s: %d new boxes\n", w, t.Insert(w))
	}
}

Time: O(L) · Extra space: O(L). Inserting a word of L letters takes L steps, no matter how many words are already stored. Space grows only by the new letters.

Watch out for

  • Overwriting an existing child with a fresh node, which wipes out every word that went through it.
  • Forgetting to set the end flag after the loop, so the word is "stored" but never found.
  • Setting the end flag on every node along the way instead of only the last one.

Quick check

  1. You insert "car" after "cat" is already stored. How many new boxes are created?
    • 3
    • 1
    • 0
  2. When is the end flag set?
    • On the first letter
    • On the last letter of the word
    • On every letter
  3. How long does one insert take for a word with 6 letters?
    • About 6 steps
    • As many steps as words stored
    • Depends on the alphabet only