Data structures · real, tested code

Implement a Trie for Autocomplete in Larzscript

The structure behind every autocomplete box: insert words, then ask what starts with a given prefix in O(prefix length), not a full scan.

Each node is just a dict of child-character-to-node plus an end-of-word flag - trie.words_with_prefix() walks down to the prefix's node once, then collects every complete word beneath it.

larzscript pkg install trie

Code

import "trie" as trie

let t = trie.new()
for w in ["cat", "car", "card", "care", "dog"] { trie.insert(t, w) }
print(trie.contains(t, "car"))
print(trie.starts_with(t, "ca"))
print(sorted(trie.words_with_prefix(t, "car")))
print(sorted(trie.all_words(t)))
Output
true
true
[car, card, care]
[car, card, care, cat, dog]