Batch Autocomplete Lookup Over a Dictionary of Words
Data Structure DesignAuto-graded · 17 test casesLast 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^41 <= len(words[i]) <= 301 <= len(prefixes) <= 10^40 <= len(prefixes[j]) <= 30- All words and prefixes consist only of lowercase English letters
atoz. - 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Remove duplicates and sort the words once. In a sorted list, all words that share a given prefix sit next to each other in a single contiguous block. So each query reduces to finding where that block starts and ends, then slicing it out.
- Preparation:
uniq = sorted(set(words)). - Query for prefix
p:lo = bisect_left(uniq, p)is the index of the first word that is>= p.hi = bisect_left(uniq, p + "{")is the index of the first word that is>= p + "{".- The answer is
uniq[lo:hi].
The character "{" comes immediately after 'z' in ASCII. Any lowercase string starting with p is therefore strictly smaller than p + "{".
Why it is correct
We claim that a lowercase word s starts with p exactly when p <= s < p + "{".
- If
sstarts withp, thenp <= s(with equality whens == p). Comparingswithp + "{": the firstlen(p)characters agree. Ifs == p, it is shorter, so it is smaller. Otherwise the next character ofsis a letter, which is less than"{", sosis smaller. - If
sdoes not start withp, eithersis a proper prefix ofp(sos < p), or the two strings first differ at some indexi < len(p). Ifs[i] < p[i]thens < p; ifs[i] > p[i]thens > p + "{". In every casesfalls outside the range.
So the matching words are exactly those in the sorted range [lo, hi). The remaining rules follow directly: duplicates are removed by set, a slice of a sorted list is sorted, no match gives lo == hi and therefore [], and iterating over prefixes in order keeps the output order. For the empty prefix, lo = 0 and hi = len(uniq) because "{" is greater than every lowercase word.
Using bisect_right(uniq, p) for the upper bound would be wrong, since it stops right after p itself and would miss longer words such as "cart" for prefix "car".
Complexity
Let N = len(words), L the maximum string length (30), Q = len(prefixes), and K the total output size.
- Preparation:
O(N * L)for hashing plusO(N log N * L)for sorting, since each comparison can costO(L). - Each query: two binary searches costing
O(L log N)each, plusO(k)to copy itskresults. - Total time:
O((N + Q) * L * log N + K). - Space:
O(N * L)for the sorted list plusO(K)for the output.
A trie is a valid alternative: walk the prefix, then traverse the subtree visiting children from a to z, using terminal flags to avoid duplicates. It handles frequent insertions better, but for a fixed dictionary the sorted array is simpler and more memory-efficient.
Reference solution
from bisect import bisect_left
from typing import List
def autocomplete_batch(words: List[str], prefixes: List[str]) -> List[List[str]]:
# Prepare once: distinct words in lexicographic order.
uniq = sorted(set(words))
out = []
for p in prefixes:
# First word >= p begins the block of words that start with p.
lo = bisect_left(uniq, p)
# '{' follows 'z' in ASCII, so p + '{' lies just past every
# lowercase string that starts with p.
hi = bisect_left(uniq, p + "{")
out.append(uniq[lo:hi])
return out