Search Suggestions System
Difficulty: Medium · Pattern: Tries · LeetCode #1268
Given products and a searchWord, after each character typed, suggest up to three products that start with the typed prefix, in lexicographic order. Return the list of suggestion lists, one per prefix.
Example
products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
→ [["mobile","moneypot","monitor"],
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"],
["mouse","mousepad"]]Hints
- In a sorted list, all strings with a given prefix are next to each other.
- Binary-search for the first string
>= prefix, then take the next three and keep the ones that start with the prefix.
Approach
Sort + binary search: sort products once. For each prefix, i = lower_bound(products, prefix). The candidates are products[i:i+3], filtered by startswith(prefix). Each step is O(log n + 3·L).
Trie alternative: insert the sorted products and store, at each node, the first three words passing through it. Each prefix step then just moves one node deeper. Mention both. The sorted version is shorter to write in an interview and just as fast in practice.
Complexity
Time: O(n log n · L) to sort + O(|searchWord| · (log n · L)). Space: O(n) for the sorted copy.
Python solution
import bisect
def suggestedProducts(products, searchWord):
products = sorted(products)
out, prefix = [], ''
for ch in searchWord:
prefix += ch
i = bisect.bisect_left(products, prefix)
out.append([p for p in products[i:i + 3] if p.startswith(prefix)])
return outJavaScript solution
function suggestedProducts(products, searchWord) {
const p = [...products].sort();
const out = [];
let prefix = '';
for (const ch of searchWord) {
prefix += ch;
let lo = 0, hi = p.length;
while (lo < hi) { const m = (lo + hi) >> 1; if (p[m] < prefix) lo = m + 1; else hi = m; }
out.push(p.slice(lo, lo + 3).filter((s) => s.startsWith(prefix)));
}
return out;
}