12/35
Part 3 of 7 · AutocompleteLearn and do

Keeping the best k on every node makes a suggestion one walk, but a lower score is costly

The other end of the trade: store on each node the best k words of its subtree, already in order. Then a suggestion is the walk to the node and nothing more. On the six items with k = 3:

NodeIts best 3, highest score first
ttea 300, tarp 120, tent 120
tetea 300, tent 120, tents 45
tentent 120, tents 45
tatarp 120
llamp 95, lantern 60

An insert now updates the list on every node along the word's path: O(L · k log k) for L letters. Inserting tea put it on the lists at t, te and tea.

Same 100,000 words, k = 5, builds timed with tracemalloc off as before:

k = 5Rank at query timeBest 5 kept on every node
Build132 ms566 ms
Memory69.8 MiB151.5 MiB
Suggest for s7,154 µs0.3 µs
Suggest for trans163 µs0.3 µs

Memory more than doubles, and building takes 4.3 times as long.

The bigger catch is change. When a word's score goes up, walk its path and re-sort each list. When it goes down, a node may need the next best word from below, and only a walk of the subtree finds it.

A middle way keeps lists only on the top two or three levels, where the subtrees are big and the query time goes.

In the editor, finish insert_ranked(trie, word, score, k). It suggests the best 3 under t and under la.