Following Prefixes in a Trie

A trie shares initial parts of keys. The presence of a path for a prefix and the presence of a complete key have separate flags.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace three strings
  2. Return matching keys
  3. Mark complete keys independently from existing branches
  4. Delete only branches no other key uses

Trace three strings

Insert car, cart, and cat. All share the path for ca. At car, mark a stored key and keep the branch for t. Searching for ca finds a prefix without a complete key there. Prefix tests supply the relation between the strings.

Return matching keys

Starting at ca, visit its descendants and include each marked node. The output order depends on how child edges are traversed. See prefix tries and path compression for more compact representations.[1]

Mark complete keys independently from existing branches

Inserting "at" and "atom" makes the node for at both terminal and a parent. A walk for "ato" succeeds as a prefix but should fail as exact membership unless that node is terminal. Keeping the two checks separate preserves both vocabulary and suggestion behavior. See prefix and suffix matches.

root → a → t (terminal) → o → m (terminal)
Prefix "ato": path exists
Exact "ato": false
Exact "at": true

Delete only branches no other key uses

Removing at can clear its terminal marker while retaining the continuation to atom. Removing atom can prune empty suffix nodes until reaching another terminal or a branch. Test exact lookup and prefix listing after removing each word in separate runs.

References

  1. Jeff Erickson, Algorithms ↩