Design Search Autocomplete System

Hard · Tries · String · Depth-First Search · Design · Trie · Sorting · Heap (Priority Queue) · Data Stream

Problem

Design a search autocomplete system. A user types a sentence one character at a time, and a sentence always ends when the user types the special character '#'.

The history is given as two arrays: sentences[i] has been typed times[i] times. The number of times a sentence has been typed is its hot degree. Implement AutocompleteSystem:

Tests replay a call sequence: the first entry names the class and its constructor arguments, each later entry is a method with its arguments, and calls returning nothing report None.

Examples

Input: ops = ["AutocompleteSystem","input","input","input","input","input"], args = [[["dog park","dog","door","cat"],[3,2,2,1]],["d"],["o"],["o"],["#"],["d"]]
Output: [null,["dog park","dog","door"],["dog park","dog","door"],["door"],[],["dog park","dog","door"]]

"dog" and "door" tie on 2 and are ordered by character. After '#', "doo" is stored with degree 1, too low to enter the top 3.

Input: ops = ["AutocompleteSystem","input","input","input","input"], args = [[["ab","ac"],[1,1]],["a"],["c"],["#"],["a"]]
Output: [null,["ab","ac"],["ac"],[],["ac","ab"]]

Typing "ac#" raises "ac" to degree 2, so it now ranks above "ab".

Constraints

Approaches

Follow-up

With millions of sentences, ranking every match on every keystroke is too slow. Cache the top three at each trie node: a lookup is then O(1) after the step, and recording a sentence updates the caches of the O(L) nodes on its path (re-rank that node’s three plus the changed sentence). Real systems also precompute these lists offline and shard the trie by first letters.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…