Delete
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Deleting from a trie means removing the end flag of the word and then trimming away branches that no other word needs. You must stop trimming at any spot that is still shared, otherwise you would accidentally erase other words.
Practical use cases
- Web app: Releasing a deleted username. When a user closes their account, their username must become available again, and it must not break suggestions for similar names like "rahul" and "rahul_k". Removing the flag and trimming only the unshared tail frees the name while keeping its neighbours safe. The same goes for emails that should be reusable after a grace period, because the trie forgets them cleanly.
- Web app: Removing a discontinued product from suggestions. An admin marks "Nokia 1100 case" as discontinued. The suggestion trie must stop offering it but still offer "Nokia 1100 charger". Deleting only the unshared end of the path does exactly that, without rebuilding the whole index. Customers stop seeing dead products in suggestions, and the memory used by the index does not keep growing.
- System: Routing tables and prefix caches. When a route expires or a cached prefix is invalidated, the entry is removed and any now-empty branch is cleaned up, keeping memory use steady over weeks of running. Careful trimming also keeps the structure from filling with empty, useless branches over time.
The story: Cleaning the Chalkboard
Aarav ran the school-trip sign-up board, a great chalk tree of names in the corridor. After the trip, a few kids dropped out and Aarav had to rub them off. He rubbed out "Chinmay" completely: all seven letters.
An hour later, Chitra complained. "Where is my name?" Oops. Her name and Chinmay's share C-H-I. By wiping the whole path, Aarav had erased the first three letters of Chitra too. The board was broken.
Mrs. Sharma showed him the safe way. "First go to the end of the name and take off the green flag. Then step back up, one box at a time. Rub out a box only if it has no other lanes under it and no flag of its own. The moment you reach a box somebody else still uses, stop."
Aarav redid it: he rubbed N-M-A-Y... and stopped at "I", because it still led to "T-R-A". Chitra was safe. This careful cleanup is trie deletion: unflag the word, then prune only the dead-end boxes from the bottom upward.
How to spot this problem, and where you need it
Items keep getting removed from your fast-lookup structure, and you need them to vanish properly without damaging other entries or leaving junk that wastes memory.
Signs you need it
- Your suggestion or lookup list still shows items that were deleted, because only the data was removed and not the search structure.
- You deleted a word and a longer or similar word stopped working, a sign of trimming too much.
- Memory keeps growing even though you delete entries, a sign of leftover empty branches.
- The problem says "remove a word from the dictionary".
Where to use it in a project
- Account closing and username or email release steps in a sign-up system.
- Admin screens that retire products, tags or keywords from autocomplete.
The solution
Walk to the last letter of the word and remove its end-of-word flag. Then go back up one step at a time: if the current node now has no children and is not the end of another word, delete it and continue upward; the moment you reach a node that is still needed, stop. This keeps shared parts and removes only the private tail.
Payoff: Before: rebuilding the entire index after each removal. After: a handful of steps, and other words stay untouched.
Explain it like I am 8
A branch is shared by many words, like a tree trunk. To remove one word, first take its flag off. Then trim from the tip of the branch back towards the trunk, but stop as soon as you reach a spot that other words still lean on.
How it works, step by step
- Walk to the last box of the word. If the path breaks or the box has no flag, the word is not there: do nothing.
- Remove the end flag of that box.
- If that box still has children, stop: longer words need it (case "do" while "dog" exists).
- Otherwise delete it and go up to the parent.
- Repeat: delete the parent only if it has no other children and no end flag; stop at the first box that fails this test.
The code in four languages
PHP
<?php
class TrieNode {
public array $kids = [];
public bool $end = false;
}
class Trie {
private TrieNode $root;
public function __construct() { $this->root = new TrieNode(); }
public function insert(string $w): void {
$n = $this->root;
foreach (str_split($w) as $ch) { $n->kids[$ch] ??= new TrieNode(); $n = $n->kids[$ch]; }
$n->end = true;
}
public function search(string $w): bool {
$n = $this->root;
foreach (str_split($w) as $ch) { if (!isset($n->kids[$ch])) return false; $n = $n->kids[$ch]; }
return $n->end;
}
public function boxes(?TrieNode $n = null): int {
$n ??= $this->root;
$c = 0;
foreach ($n->kids as $k) { $c += 1 + $this->boxes($k); }
return $c;
}
public function delete(string $word): void { $this->remove($this->root, $word, 0); }
// Returns true if this node is now useless and its parent may drop it.
private function remove(TrieNode $n, string $w, int $i): bool {
if ($i === strlen($w)) {
if (!$n->end) { return false; } // word was never stored
$n->end = false; // take the flag off
return count($n->kids) === 0; // leaf? then drop it
}
$ch = $w[$i];
if (!isset($n->kids[$ch])) { return false; } // path broken: nothing to do
if ($this->remove($n->kids[$ch], $w, $i + 1)) {
unset($n->kids[$ch]); // prune the dead box
}
return !$n->end && count($n->kids) === 0; // am I dead too?
}
}
$t = new Trie();
foreach (['cat', 'car', 'cub', 'do', 'dog'] as $w) { $t->insert($w); }
echo 'boxes: ' . $t->boxes() . PHP_EOL; // 9
$t->delete('cub');
echo 'after cub: ' . $t->boxes() . PHP_EOL; // 7 (u and b pruned)
$t->delete('do');
echo 'after do: ' . $t->boxes() . ', dog? ' . ($t->search('dog') ? 'yes' : 'no') . ', do? ' . ($t->search('do') ? 'yes' : 'no') . PHP_EOL;JavaScript
class TrieNode {
constructor() { this.kids = {}; this.end = false; }
}
class Trie {
constructor() { this.root = new TrieNode(); }
insert(w) {
let n = this.root;
for (const ch of w) { if (!n.kids[ch]) n.kids[ch] = new TrieNode(); n = n.kids[ch]; }
n.end = true;
}
search(w) {
let n = this.root;
for (const ch of w) { if (!n.kids[ch]) return false; n = n.kids[ch]; }
return n.end;
}
boxes(n = this.root) {
let c = 0;
for (const ch in n.kids) c += 1 + this.boxes(n.kids[ch]);
return c;
}
delete(word) { this.remove(this.root, word, 0); }
// Returns true if this node is now useless and its parent may drop it.
remove(n, w, i) {
if (i === w.length) {
if (!n.end) return false; // word was never stored
n.end = false; // take the flag off
return Object.keys(n.kids).length === 0; // leaf? then drop it
}
const ch = w[i];
if (!n.kids[ch]) return false; // path broken: nothing to do
if (this.remove(n.kids[ch], w, i + 1)) {
delete n.kids[ch]; // prune the dead box
}
return !n.end && Object.keys(n.kids).length === 0; // am I dead too?
}
}
const t = new Trie();
for (const w of ['cat', 'car', 'cub', 'do', 'dog']) t.insert(w);
console.log('boxes: ' + t.boxes()); // 9
t.delete('cub');
console.log('after cub: ' + t.boxes()); // 7 (u and b pruned)
t.delete('do');
console.log('after do: ' + t.boxes() + ', dog? ' + (t.search('dog') ? 'yes' : 'no') + ', do? ' + (t.search('do') ? 'yes' : 'no'));Java
import java.util.*;
public class Main {
static class TrieNode {
Map<Character, TrieNode> kids = new HashMap<>();
boolean end = false;
}
static class Trie {
private final TrieNode root = new TrieNode();
void insert(String w) {
TrieNode n = root;
for (char ch : w.toCharArray()) {
n.kids.putIfAbsent(ch, new TrieNode());
n = n.kids.get(ch);
}
n.end = true;
}
boolean search(String w) {
TrieNode n = root;
for (char ch : w.toCharArray()) {
if (!n.kids.containsKey(ch)) return false;
n = n.kids.get(ch);
}
return n.end;
}
int boxes() { return boxes(root); }
private int boxes(TrieNode n) {
int c = 0;
for (TrieNode k : n.kids.values()) c += 1 + boxes(k);
return c;
}
void delete(String word) { remove(root, word, 0); }
// Returns true if this node is now useless and its parent may drop it.
private boolean remove(TrieNode n, String w, int i) {
if (i == w.length()) {
if (!n.end) return false; // word was never stored
n.end = false; // take the flag off
return n.kids.isEmpty(); // leaf? then drop it
}
char ch = w.charAt(i);
if (!n.kids.containsKey(ch)) return false; // path broken: nothing to do
if (remove(n.kids.get(ch), w, i + 1)) {
n.kids.remove(ch); // prune the dead box
}
return !n.end && n.kids.isEmpty(); // am I dead too?
}
}
public static void main(String[] args) {
Trie t = new Trie();
for (String w : new String[]{"cat", "car", "cub", "do", "dog"}) t.insert(w);
System.out.println("boxes: " + t.boxes()); // 9
t.delete("cub");
System.out.println("after cub: " + t.boxes()); // 7 (u and b pruned)
t.delete("do");
System.out.println("after do: " + t.boxes() + ", dog? " + (t.search("dog") ? "yes" : "no")
+ ", do? " + (t.search("do") ? "yes" : "no"));
}
}Go
package main
import "fmt"
type TrieNode struct {
kids map[rune]*TrieNode
end bool
}
func newTrieNode() *TrieNode { return &TrieNode{kids: map[rune]*TrieNode{}} }
type Trie struct {
root *TrieNode
}
func NewTrie() *Trie { return &Trie{root: newTrieNode()} }
func (t *Trie) Insert(w string) {
n := t.root
for _, ch := range w {
if n.kids[ch] == nil {
n.kids[ch] = newTrieNode()
}
n = n.kids[ch]
}
n.end = true
}
func (t *Trie) Search(w string) bool {
n := t.root
for _, ch := range w {
if n.kids[ch] == nil {
return false
}
n = n.kids[ch]
}
return n.end
}
func boxes(n *TrieNode) int {
c := 0
for _, k := range n.kids {
c += 1 + boxes(k)
}
return c
}
func (t *Trie) Delete(word string) { remove(t.root, []rune(word), 0) }
// remove returns true if this node is now useless and its parent may drop it.
func remove(n *TrieNode, w []rune, i int) bool {
if i == len(w) {
if !n.end {
return false // word was never stored
}
n.end = false // take the flag off
return len(n.kids) == 0 // leaf? then drop it
}
ch := w[i]
kid := n.kids[ch]
if kid == nil {
return false // path broken: nothing to do
}
if remove(kid, w, i+1) {
delete(n.kids, ch) // prune the dead box
}
return !n.end && len(n.kids) == 0 // am I dead too?
}
func yesNo(b bool) string {
if b {
return "yes"
}
return "no"
}
func main() {
t := NewTrie()
for _, w := range []string{"cat", "car", "cub", "do", "dog"} {
t.Insert(w)
}
fmt.Println("boxes:", boxes(t.root)) // 9
t.Delete("cub")
fmt.Println("after cub:", boxes(t.root)) // 7 (u and b pruned)
t.Delete("do")
fmt.Printf("after do: %d, dog? %s, do? %s\n", boxes(t.root), yesNo(t.Search("dog")), yesNo(t.Search("do")))
}Time: O(L) · Extra space: O(L). One walk down and one climb back up for a word of L letters; the recursion uses L stack frames.
Watch out for
- Deleting every box on the word's path, which destroys other words that share it.
- Removing a box that still has the end flag (it is another stored word, like "do" inside "dog").
- Trying to delete a word that is not stored and accidentally clearing a flag or boxes anyway.
Quick check
- You delete "do" while "dog" is stored. What happens?
- Boxes d and o are removed
- Only the flag on o is removed
- dog is deleted too
- When may you remove a box while climbing back up?
- Always
- When it has no children and no end flag
- Only the root
- What should delete do for a word that is not in the trie?
- Remove the last letters anyway
- Nothing at all
- Throw away the whole trie