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]
Related
larztrieThe structure behind autocomplete - insert words, query by prefix→Implement a Stack and a Queue in LarzscriptThe two most basic linear data structures - last-in-first-out and first-in-first-out - named explicitly instead of just using a bare list.→Implement a Binary Search Tree in LarzscriptInsert values into a binary search tree and read them back in sorted order.→Implement a Priority Queue (Binary Heap) in LarzscriptAlways get the smallest (or, with a key function, largest/custom-ordered) item next - the classic array-backed binary heap.→