Search Suggestions System
Search Suggestions System is a medium tries problem solved with the basics pattern.
The best approach, optimal (trie with three suggestions per node), runs in O(n log n · L + S + m) time and O(S) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from sort, then scan for each prefix up.
Problem
You are given an array of distinct product names products and a string searchWord, all made of lowercase letters. Imagine typing searchWord into a search box one character at a time. After each character, the box shows at most three product names that start with the text typed so far. When more than three products match, it shows the three that come first in lexicographic order.
Return a list with one entry per character of searchWord: the entry for the i-th character is the list of suggestions shown once the first i characters have been typed (an empty list if nothing matches).
Examples
Example 1
- Input
products = ["melon", "mango", "map", "maple", "mat", "milk"], searchWord = "map"- Output
[["mango", "map", "maple"], ["mango", "map", "maple"], ["map", "maple"]]- Why
- In sorted order the products are mango, map, maple, mat, melon, milk. All six start with "m" and four start with "ma"; each time the first three are kept. Only map and maple start with "map".
Example 2
- Input
products = ["ruby", "rust", "rose"], searchWord = "rot"- Output
[["rose", "ruby", "rust"], ["rose"], []]- Why
- Every product starts with "r", only rose starts with "ro", and nothing starts with "rot", so the last list is empty.
Example 3
- Input
products = ["kiwi"], searchWord = "fig"- Output
[[], [], []]- Why
- No product starts with "f", so no longer prefix can match either. There is still one (empty) list per typed character.
Constraints
1 <= products.length <= 10001 <= products[i].length <= 30001 <= sum(products[i].length) <= 2 * 10^4- All strings in
productsare distinct. 1 <= searchWord.length <= 1000products[i]andsearchWordconsist of lowercase English letters.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Sort, then scan for each prefix | O(n log n · L + m · n · m) | O(m) |
| Sort + binary search | O(n log n · L + m · (m log n)) | O(m) |
| Optimal (trie with three suggestions per node) | O(n log n · L + S + m) | O(S) |
1Sort, then scan for each prefix
O(n log n · L + m · n · m)Sorting compares strings of length up to L. Then, for each of the m prefixes, up to n products are checked, each check costing up to m character comparisons.O(m)Apart from the output, only the current prefix is stored.Sort the products so that any group of matches comes out in lexicographic order. For each prefix of the search word, scan the sorted list from the start and collect the first three products that begin with that prefix.
- Sort products.
- For each length 1..m, take prefix = searchWord[0..len).
- Scan the sorted products and add each one that starts with prefix, stopping after three.
- Append the list (possibly empty) to the result.
class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
Arrays.sort(products);
List<List<String>> result = new ArrayList<>();
for (int len = 1; len <= searchWord.length(); len++) {
String prefix = searchWord.substring(0, len);
List<String> list = new ArrayList<>();
for (String p : products) {
if (p.startsWith(prefix)) {
list.add(p);
if (list.size() == 3) break;
}
}
result.add(list);
}
return result;
}
}class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
result = []
for length in range(1, len(searchWord) + 1):
prefix = searchWord[:length]
lst = []
for p in products:
if p.startswith(prefix):
lst.append(p)
if len(lst) == 3:
break
result.append(lst)
return resultclass Solution {
public:
vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
sort(products.begin(), products.end());
vector<vector<string>> result;
for (int len = 1; len <= (int)searchWord.size(); len++) {
string prefix = searchWord.substr(0, len);
vector<string> list;
for (const string& p : products) {
if (p.compare(0, prefix.size(), prefix) == 0) {
list.push_back(p);
if (list.size() == 3) break;
}
}
result.push_back(list);
}
return result;
}
};function suggestedProducts(products, searchWord) {
products.sort();
const result = [];
for (let len = 1; len <= searchWord.length; len++) {
const prefix = searchWord.substring(0, len);
const list = [];
for (const p of products) {
if (p.startsWith(prefix)) {
list.push(p);
if (list.length === 3) break;
}
}
result.push(list);
}
return result;
}2Sort + binary search
O(n log n · L + m · (m log n))Sorting costs n log n comparisons of strings up to L long. Each of the m prefixes needs log n comparisons of up to m characters, plus three prefix checks.O(m)Apart from the output, only the prefix string is stored.In the sorted list, the products that start with a prefix sit in one contiguous block, and that block begins at the first product that is not smaller than the prefix. Binary search finds that position; the suggestions are the next (at most) three products that still start with the prefix.
- Sort products.
- Grow prefix one character at a time.
- Binary search for lo = the first index with products[lo] >= prefix.
- Take products[lo], products[lo + 1], products[lo + 2] while they exist and start with prefix.
class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
Arrays.sort(products);
List<List<String>> result = new ArrayList<>();
String prefix = "";
for (char c : searchWord.toCharArray()) {
prefix += c;
int lo = 0, hi = products.length;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (products[mid].compareTo(prefix) < 0) lo = mid + 1;
else hi = mid;
}
List<String> list = new ArrayList<>();
for (int i = lo; i < products.length && i < lo + 3; i++) {
if (!products[i].startsWith(prefix)) break;
list.add(products[i]);
}
result.add(list);
}
return result;
}
}class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
result = []
prefix = ""
for c in searchWord:
prefix += c
lo, hi = 0, len(products)
while lo < hi:
mid = (lo + hi) // 2
if products[mid] < prefix:
lo = mid + 1
else:
hi = mid
lst = []
for i in range(lo, min(len(products), lo + 3)):
if not products[i].startswith(prefix):
break
lst.append(products[i])
result.append(lst)
return resultclass Solution {
public:
vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
sort(products.begin(), products.end());
vector<vector<string>> result;
string prefix = "";
int n = (int)products.size();
for (char c : searchWord) {
prefix += c;
int lo = 0, hi = n;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (products[mid] < prefix) lo = mid + 1;
else hi = mid;
}
vector<string> list;
for (int i = lo; i < n && i < lo + 3; i++) {
if (products[i].compare(0, prefix.size(), prefix) != 0) break;
list.push_back(products[i]);
}
result.push_back(list);
}
return result;
}
};function suggestedProducts(products, searchWord) {
products.sort();
const result = [];
let prefix = "";
for (const c of searchWord) {
prefix += c;
let lo = 0, hi = products.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (products[mid] < prefix) lo = mid + 1;
else hi = mid;
}
const list = [];
for (let i = lo; i < products.length && i < lo + 3; i++) {
if (!products[i].startsWith(prefix)) break;
list.push(products[i]);
}
result.push(list);
}
return result;
}3Optimal (trie with three suggestions per node)
O(n log n · L + S + m)Sorting dominates. Building the trie touches each of the S characters once, and the walk is one step per character of the search word.O(S)Up to S trie nodes (S = total length of all products), each holding at most three references.Insert the sorted products into a trie. Because they arrive in lexicographic order, the first three words that pass through a node are exactly the three smallest words with that node's prefix, so each node simply keeps the first three it sees. Then walk the search word down the trie and read each node's list; once the walk falls off the trie, every remaining list is empty.
- Sort products.
- Insert each product; at every node on its path, append the product if the node holds fewer than three.
- Walk the search word from the root, one character per step.
- While the node exists, its list is the answer for this prefix; after a missing child, append empty lists.
class Solution {
private static class Node {
Node[] next = new Node[26];
List<String> top = new ArrayList<>();
}
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
Arrays.sort(products);
Node root = new Node();
for (String p : products) {
Node cur = root;
for (char c : p.toCharArray()) {
int i = c - 'a';
if (cur.next[i] == null) cur.next[i] = new Node();
cur = cur.next[i];
if (cur.top.size() < 3) cur.top.add(p);
}
}
List<List<String>> result = new ArrayList<>();
Node cur = root;
for (char c : searchWord.toCharArray()) {
if (cur != null) cur = cur.next[c - 'a'];
result.add(cur == null ? new ArrayList<>() : cur.top);
}
return result;
}
}class TrieNode:
def __init__(self):
self.next = {}
self.top = []
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
root = TrieNode()
for p in products:
cur = root
for c in p:
if c not in cur.next:
cur.next[c] = TrieNode()
cur = cur.next[c]
if len(cur.top) < 3:
cur.top.append(p)
result = []
cur = root
for c in searchWord:
if cur is not None:
cur = cur.next.get(c)
result.append([] if cur is None else list(cur.top))
return resultclass Solution {
struct Node {
Node* next[26] = {nullptr};
vector<string> top;
};
public:
vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
sort(products.begin(), products.end());
Node* root = new Node();
for (const string& p : products) {
Node* cur = root;
for (char c : p) {
int i = c - 'a';
if (!cur->next[i]) cur->next[i] = new Node();
cur = cur->next[i];
if (cur->top.size() < 3) cur->top.push_back(p);
}
}
vector<vector<string>> result;
Node* cur = root;
for (char c : searchWord) {
if (cur) cur = cur->next[c - 'a'];
result.push_back(cur ? cur->top : vector<string>());
}
return result;
}
};function suggestedProducts(products, searchWord) {
products.sort();
const newNode = () => ({ next: new Map(), top: [] });
const root = newNode();
for (const p of products) {
let cur = root;
for (const c of p) {
if (!cur.next.has(c)) cur.next.set(c, newNode());
cur = cur.next.get(c);
if (cur.top.length < 3) cur.top.push(p);
}
}
const result = [];
let cur = root;
for (const c of searchWord) {
if (cur !== null) cur = cur.next.get(c) ?? null;
result.push(cur === null ? [] : [...cur.top]);
}
return result;
}Edge cases to test
- No product matches even the first letter (every list is empty)
- Matches stop part way through the search word (the remaining lists are empty)
- Fewer than three products share a prefix
- A product equal to a prefix sorts before its longer extensions
- The search word is longer than every product
- The input array is not sorted
Hints
Hint 1
Sort the products first. Then the products sharing any prefix form one contiguous block, already in lexicographic order.
Hint 2
For a prefix, binary search for the first product that is not smaller than it; the suggestions are at most the next three products, as long as they still start with the prefix.
Hint 3
Alternatively, build a trie from the sorted products and let every node keep the first three words that pass through it.
FAQ
What is the best time complexity for Search Suggestions System?
Optimal (trie with three suggestions per node) runs in O(n log n · L + S + m) time and O(S) extra space. Sorting dominates. Building the trie touches each of the S characters once, and the walk is one step per character of the search word.
Which pattern does Search Suggestions System use?
It is a tries problem that uses the basics pattern. Other problems with the same pattern: Implement Trie (Prefix Tree), Implement Trie ll, Design In-Memory File System.
Is there a brute force solution for Search Suggestions System?
Yes. Sort, then scan for each prefix takes O(n log n · L + m · n · m) time and O(m) space. Sort the products so that any group of matches comes out in lexicographic order.
Which edge cases should I test for Search Suggestions System?
No product matches even the first letter (every list is empty); Matches stop part way through the search word (the remaining lists are empty); Fewer than three products share a prefix; A product equal to a prefix sorts before its longer extensions; The search word is longer than every product; The input array is not sorted.