Polski

Search suggestions with a trie

A search box suggests the most popular phrases that start with the typed prefix. A prefix tree (trie), popularity counters and a deterministic order.

medium · typescript · javascript · python · csharp · java · go · 20 XP

The documentation search should suggest phrases as the user types. Every search for a phrase increases its popularity, and the suggestions for a prefix are the most popular phrases starting with that prefix. There are tens of thousands of phrases, so scanning all of them on every keystroke is not an option.

Task

A class Autocomplete:

  • add(word) – records one search for the word (its counter +1; the first call adds the word),
  • suggest(prefix, limit = 3) – returns at most limit words starting with prefix (the prefix itself counts if it was added), sorted by counter descending and alphabetically for ties; an empty prefix = all words; no matches = an empty list.

Words consist of lowercase letters a–z. Names: JS/TS add, suggest; Python add, suggest; C# Add, Suggest; Java add, suggest(prefix) and suggest(prefix, limit); Go NewAutocomplete(), Add, Suggest(prefix, limit).

Example

Operationssuggest("ja")
add("java") ×3, add("javascript") ×5, add("jakarta") ×1["javascript", "java", "jakarta"]
add("java") ×3 more["java", "javascript", "jakarta"]
suggest("ja", 1)["java"]
suggest("jx")[]

Constraints

  • Up to 60,000 add calls (words up to 20 letters) and 2,000 suggest calls, 1 ≤ limit ≤ 10.

Expected complexity

add: O(L) for a word of length L. suggest: O(P + m log m), where P is the prefix length and m the number of words under the prefix (or better, with a heap of size limit or lists of best words in nodes).