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:
| Node | Its best 3, highest score first |
|---|---|
t | tea 300, tarp 120, tent 120 |
te | tea 300, tent 120, tents 45 |
ten | tent 120, tents 45 |
ta | tarp 120 |
l | lamp 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 = 5 | Rank at query time | Best 5 kept on every node |
|---|---|---|
| Build | 132 ms | 566 ms |
| Memory | 69.8 MiB | 151.5 MiB |
Suggest for s | 7,154 µs | 0.3 µs |
Suggest for trans | 163 µs | 0.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.