3.4.14 · D3Trees

Worked examples — Trie (prefix tree) — insert, search, startsWith, applications (autocomplete, spell check)

2,544 words12 min readBack to topic

The scenario matrix

Every problem a trie can throw at you falls into one of these cells. The matrix is our map — each worked example below is tagged with the cell it fills.

Cell Class of scenario What makes it tricky Filled by
A Insert into empty trie no shared road yet — every char is new Ex 1
B Insert sharing a prefix reuse existing road, branch late Ex 2
C search a word that IS present must end on isEnd = True Ex 3
D search a proper prefix (present as road, NOT as word) path exists but isEnd = False Ex 4
E search a word whose path breaks early missing child → fail at char k Ex 5
F startsWith vs search on same string same walk, different final question Ex 6
G Degenerate input: empty string "" zero characters — the loop never runs Ex 7
H One word is a strict prefix of another (carcard) isEnd on an internal node Ex 8
I Delete without breaking a longer word unset flag, prune carefully Ex 9
J Real-world / exam twist: autocomplete ranking + limiting case (no completions) DFS a subtree, handle the empty result Ex 10

The running dictionary for most examples is . See the tree we build in Ex 1–2:

Figure — Trie (prefix tree) — insert, search, startsWith, applications (autocomplete, spell check)

Worked Examples


Recall Quick self-test across the matrix

On : search("ca") ::: False (path exists, no word ends — Cell D) startsWith("ca") ::: True (road exists — Cell F) search("cat") ::: False, breaks at index 2 (Cell E) search("card") after inserting car ::: True — both flags coexist (Cell H) search("") before any insert("") ::: False (root flag defaults false — Cell G) autocomplete("z") ::: [] empty list, graceful (Cell J limit)


Active Recall

In search, why do we return node.isEnd instead of True after the walk succeeds?
A successful walk only proves the path/prefix exists; a word must end there, which only isEnd confirms.
When deleting a word, when may we prune a node?
Only if it has no children AND its own isEnd is False; otherwise other words still need it.
What does insert("") do?
The character loop runs zero times, so it sets isEnd = True on the root (the empty-string node).
Why does autocomplete("z") return [] and not crash?
The prefix walk finds no z-child, breaks immediately, and returns an empty list — no word has that prefix.