- Interview Questions
- /
- Problems
- /
- Search Suggestions System
Search Suggestions System
Return up to three alphabetically first product names for every prefix of a search word as it is typed. A test of sorting plus binary search or a trie for prefix lookups. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're building the autocomplete box for a store. You have an array of distinct lowercase product names products and the word a shopper is typing, searchWord.
After the shopper types each character, show up to three product names that start with everything typed so far. If more than three products match, show the three that come first in alphabetical (lexicographic) order.
Return an array with one entry per character of searchWord. Entry i is the list of suggestions after the first i + 1 characters have been typed, in alphabetical order. If nothing matches, that entry is an empty list.
Example 1
- Input
- products = ["pencil", "pen", "pepper", "pear", "penguin", "plate"], searchWord = "pen"
- Output
- [["pear", "pen", "pencil"], ["pear", "pen", "pencil"], ["pen", "pencil", "penguin"]]
Every product but "plate" starts with "pe", and the first three alphabetically are pear, pen, pencil. Only pen, pencil and penguin start with "pen".
Example 2
- Input
- products = ["kiwi"], searchWord = "kiwi"
- Output
- [["kiwi"], ["kiwi"], ["kiwi"], ["kiwi"]]
Example 3
- Input
- products = ["mango", "melon"], searchWord = "mix"
- Output
- [["mango", "melon"], [], []]
Once "mi" is typed, nothing matches, and nothing can match any longer prefix either.
Constraints
- 1 ≤ products.length ≤ 3000
- 1 ≤ products[i].length, searchWord.length ≤ 3000
- All product names are distinct and use only lowercase English letters.
- searchWord uses only lowercase English letters.
Practice
Runs 11 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Search Suggestions System in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Search Suggestions System
Pattern: Sort, then binary search each prefix
Once the products are sorted, every product that starts with a given prefix sits in one contiguous block, and that block begins exactly where the prefix itself would be inserted. So the three suggestions for a prefix are just the first three names at or after that insertion point, as long as they still start with the prefix.
That turns each keystroke into one binary search instead of a scan over every product. A trie gives the same answer by walking one node per character, but sorting plus binary search needs far less code and is what most interviewers expect first.
Approach 1: Filter for every prefix
Sort the products. For each prefix, scan the whole list, keep the names that start with the prefix, and take the first three. Simple and correct, but it reads every product once per typed character.
Time O(n log n · L + m · n · L) for n products, word length m, name length L · Space O(1) beyond the output
Approach 2: Trie with top three stored at each node
Insert every product into a trie. At each node keep the three alphabetically smallest names passing through it (insert products in sorted order and only append while a node holds fewer than three). Then walk the trie one character at a time, reading each node's list, and emit empty lists once the walk falls off the trie.
Time O(total characters + m) · Space O(total characters)
Approach 3: Sort and binary search
- Sort
products. - For each prefix of
searchWord, binary search for the first name that is>= prefix. - Look at up to three names from that position and keep the ones that start with the prefix.
Because prefixes only grow, the insertion point never moves left, so you can also start each search from the previous result.
Time O(n log n · L + m · log n · L) · Space O(1) beyond the sort and output
| Approach | Time | Space |
|---|---|---|
| Filter for every prefix | O(n log n · L + m · n · L) for n products, word length m, name length L | O(1) beyond the output |
| Trie with top three stored at each node | O(total characters + m) | O(total characters) |
| Sort and binary search | O(n log n · L + m · log n · L) | O(1) beyond the sort and output |
Solution code
Try the practice editor first. Both solutions pass every test above.
Search Suggestions System solution in Python
def suggested_products(products: list[str], search_word: str) -> list[list[str]]:
products = sorted(products)
result = []
lo = 0
prefix = ""
for ch in search_word:
prefix += ch
lo = bisect.bisect_left(products, prefix, lo)
result.append([p for p in products[lo:lo + 3] if p.startswith(prefix)])
return resultSearch Suggestions System solution in JavaScript
function suggestedProducts(products, searchWord) {
const sorted = [...products].sort();
const result = [];
let lo = 0;
let prefix = '';
for (const ch of searchWord) {
prefix += ch;
let left = lo;
let right = sorted.length;
while (left < right) {
const mid = (left + right) >> 1;
if (sorted[mid] < prefix) left = mid + 1;
else right = mid;
}
lo = left;
result.push(
sorted.slice(lo, lo + 3).filter((p) => p.startsWith(prefix))
);
}
return result;
}Common mistakes
- Returning matches in input order instead of alphabetical order.
- Stopping the output early once a prefix has no matches. The answer still needs one (empty) entry per typed character.
- Taking three names after the insertion point without checking that each one actually starts with the prefix.
- Using a case or locale aware comparison that does not match plain character order.
What interviewers look for
Say the key fact first: "after sorting, all names with the same prefix are adjacent, and the block starts at the prefix's insertion point." Once that lands, binary search is the obvious tool and the code is short.
Interviewers often ask about a trie because this looks like an autocomplete problem. It's worth explaining the trade-off: a trie answers each keystroke in O(1) after a heavier build, which matters when the catalog is fixed and queries are many, while the sorted array is simpler and lighter on memory.
Follow-up questions
How would this work for a live autocomplete with millions of queries?
Build the index once. A trie where each node caches its top suggestions answers every keystroke by following one child pointer, so the per-keystroke cost does not depend on the catalog size. The sorted array also works and can be memory mapped.
What if suggestions should be ranked by popularity instead of alphabetically?
Store a popularity score per product and keep the top three by score at each trie node, updating those small lists when a score changes. With a sorted array you would have to scan the whole prefix block, so the trie wins here.
How would you handle the shopper deleting characters?
Keep a stack of the trie nodes (or insertion indices) for each prefix typed so far. Backspace pops the stack and the previous suggestions are available immediately without recomputing.
Companies that ask Search Suggestions System
Search Suggestions System is tagged by 110 companies in our interview dataset. The score shows how often it comes up at each company.
- Wepay100%
- Chargebee100%
- Squarepoint Capital100%
- Swisscom100%
- Skydio100%
- Noom100%
- Citiustech92%
- Sambanova Systems90%
- Appier90%
- Workiva90%
- Ubs89.4%
- Vaxcyte89%
- Esri89%
- Wixcom87.3%
- N2687%
- Traveloka87%
- Project4485%
- Sabre83%
- Valon83%
- DoorDash82.5%
- Etched82%
- Talabat82%
- Soundcloud82%
- Docusign81.7%
and 86 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required