KatInterview

Batch Autocomplete Lookup Over a Dictionary of Words

Data Structure DesignAuto-graded · 17 test cases
MediumAuto-gradedData Structure Designbinary-searchtriesorting

Last updated

Answer many prefix queries against a word list, returning sorted distinct matches for each, using sorting and binary search or a trie instead of rescanning the list per query.

Batch Autocomplete Lookup

You are building the lookup core of an autocomplete feature. You have a dictionary of words that is fixed, and a batch of typed fragments (prefixes). For each fragment, report every dictionary word that begins with it.

The dictionary is conceptually prepared once and then consulted many times, so answering a single fragment should not require scanning the entire dictionary.

Implement a function that receives the dictionary and the whole batch of fragments, and returns one result list per fragment.

Matching rules

  • A word matches a fragment if the word's first len(fragment) characters are exactly the fragment. A word always matches itself, and the empty fragment "" matches every word.
  • The dictionary may contain repeated words. In any single result, each distinct word appears at most once.
  • Each result is sorted in ascending lexicographic (dictionary) order. If nothing matches, the result is an empty list.
  • Results appear in the same order as the fragments in the input.

Input

  • words: a list of strings, the dictionary (may contain duplicates).
  • prefixes: a list of strings, the fragments to look up.

Output

A list of lists of strings. The j-th inner list holds the distinct dictionary words that start with prefixes[j], in ascending order.

Constraints

  • 1 <= len(words) <= 10^4
  • 1 <= len(words[i]) <= 30
  • 1 <= len(prefixes) <= 10^4
  • 0 <= len(prefixes[j]) <= 30
  • All words and prefixes consist only of lowercase English letters a to z.
  • The total number of words across all results is at most 2 * 10^5.

Examples

Example 1

Input: autocomplete_batch(['lidar', 'lane', 'radar', 'lanes', 'lidar', 'map'], ['la', 'lid', 'r', 'x', ''])

Output: [['lane', 'lanes'], ['lidar'], ['radar'], [], ['lane', 'lanes', 'lidar', 'map', 'radar']]

Example 2

Input: autocomplete_batch(['car', 'cart', 'carbon', 'cat', 'car'], ['car', 'cart', 'ca', 'carts'])

Output: [['car', 'carbon', 'cart'], ['cart'], ['car', 'carbon', 'cart', 'cat'], []]

Hints

Hint 1

Think about what the distinct words look like once they are sorted. Where do all the words sharing one prefix end up relative to each other?

Hint 2

If the matches form one contiguous block in the sorted list, a query only needs the block's start and end positions. Binary search can find both.

Hint 3

The start of the block is the first word that is >= the prefix. For the end, find a string that sorts just after every lowercase string beginning with the prefix, for example the prefix followed by the character right after 'z'. Remember bisect_right on the prefix alone is not enough.