Search Suggestions System (LeetCode 1268): Solution and Explanation
After each character of searchWord is typed, suggest up to three products that start with the typed prefix, choosing the lexicographically smallest when more than three match.
Intuition
Autocomplete wants the smallest matching words, so sort the products first. Sorting has a second, more useful effect: all words that share a prefix end up next to each other in one contiguous block.
Typing another letter only makes the prefix longer, and the block for a longer prefix sits inside the block for the shorter one. So you never need to search the whole list again. You keep a window [lo, hi] and shrink it.
When the i-th character c is typed, the word at lo either has c at index i or it does not. If it does not (or it is too short), it can never match any later prefix either, so lo moves down past it. The same check moves hi up from the bottom.
After both pointers settle, the window holds exactly the matching words in sorted order, and the first three of them are the suggestions. If the pointers cross, nothing matches this prefix or any longer one.
Approach: Sort, then shrink a window with two pointers
- Sort
productslexicographically. - Set
lo = 0andhi = len(products) - 1. - For each index i and character c of
searchWord, advancelowhileproducts[lo]is shorter than i + 1 or has a different character at i. Retreathiwith the same test. - Append
products[lo : min(lo + 3, hi + 1)], which is empty whenlo > hi. - Return the list of suggestion lists.
Step-by-step example
products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
- Sorted: mobile, moneypot, monitor, mouse, mousepad. The window is [0, 4].
- Type m: every word starts with m, so the window stays [0, 4]. Suggest mobile, moneypot, monitor.
- Type o: every word has o at index 1. Same suggestions.
- Type u: lo skips mobile (b), moneypot (n) and monitor (n) and stops at mouse, index 3. hi stays at mousepad. Suggest mouse, mousepad.
- Type s and e: both remaining words match. Suggest mouse, mousepad twice more.
- Return the five lists.
Code: Python, Java, C++
1class Solution:
2 def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
3 products.sort()
4 lo, hi = 0, len(products) - 1
5 result = []
6 for i, c in enumerate(searchWord):
7 while lo <= hi and (len(products[lo]) <= i or products[lo][i] != c):
8 lo += 1
9 while lo <= hi and (len(products[hi]) <= i or products[hi][i] != c):
10 hi -= 1
11 result.append(products[lo:min(lo + 3, hi + 1)])
12 return result1class Solution {
2 public List<List<String>> suggestedProducts(String[] products, String searchWord) {
3 Arrays.sort(products);
4 int lo = 0, hi = products.length - 1;
5 List<List<String>> result = new ArrayList<>();
6 for (int i = 0; i < searchWord.length(); i++) {
7 char c = searchWord.charAt(i);
8 while (lo <= hi && (products[lo].length() <= i || products[lo].charAt(i) != c)) {
9 lo++;
10 }
11 while (lo <= hi && (products[hi].length() <= i || products[hi].charAt(i) != c)) {
12 hi--;
13 }
14 List<String> top = new ArrayList<>();
15 for (int k = lo; k < Math.min(lo + 3, hi + 1); k++) {
16 top.add(products[k]);
17 }
18 result.add(top);
19 }
20 return result;
21 }
22}1class Solution {
2public:
3 vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
4 sort(products.begin(), products.end());
5 int lo = 0, hi = (int) products.size() - 1;
6 vector<vector<string>> result;
7 for (int i = 0; i < (int) searchWord.size(); i++) {
8 char c = searchWord[i];
9 while (lo <= hi && ((int) products[lo].size() <= i || products[lo][i] != c)) {
10 lo++;
11 }
12 while (lo <= hi && ((int) products[hi].size() <= i || products[hi][i] != c)) {
13 hi--;
14 }
15 vector<string> top;
16 for (int k = lo; k < min(lo + 3, hi + 1); k++) {
17 top.push_back(products[k]);
18 }
19 result.push_back(top);
20 }
21 return result;
22 }
23};Time and space complexity
O(n log n * L + n + m)
Sorting n strings costs O(n log n) comparisons, each up to L characters. The pointers only move inward, so all pointer moves together are O(n), and there are m prefixes, each copying at most three words.
O(1)
Apart from the sort and the output, only two pointers are used.
Other approaches
Binary search per prefix (time O(n log n * L + m log n * L), space O(1))
After sorting, use bisect_left to find the first word that is not smaller than the prefix, then check the next three words for the prefix. It is easy to write and does O(log n) comparisons per prefix.
Trie with top three per node (time O(total length + m), space O(total length))
Insert sorted products into a trie and store at each node the first three words that pass through it. Then walk the trie along searchWord. It answers each prefix in O(1) but uses memory proportional to the total length of all products.
Common mistakes
- Forgetting the length check. A word shorter than the prefix must be removed before reading its character at index i.
- Returning to the full list for every prefix. It works but throws away the fact that the matching block only shrinks.
- Stopping the output early once nothing matches. The answer needs one list per typed character, so later prefixes still get empty lists.
- Taking three words from the window without capping at
hi + 1when fewer than three remain.
Frequently asked questions
Why can lo never move back up?
A word skipped by lo does not match the current prefix. Every later prefix extends the current one, so that word cannot match any of them either.
Is a trie better here?
A trie is the classic autocomplete structure and is great when the product list is fixed and queried many times. For a single search word, sorting plus two pointers is shorter and uses less memory.
What does the output look like when nothing matches?
Each remaining prefix gets an empty list. For products ["havana"] and searchWord "tatiana", the output is seven empty lists.