Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get a list of distinct lowercase products and a searchWord. Imagine typing searchWord into a search box, one letter at a time. After each letter, show up to three products that start with the letters typed so far. If more than three match, show the three that come first alphabetically (lexicographically).
Return a list with one entry per typed letter: len(searchWord) lists in total.
Example: products ["mobile", "mouse", "moneypot", "monitor", "mousepad"], search word "mouse".
| Typed | Matches, sorted | Shown |
|---|---|---|
m | mobile, moneypot, monitor, mouse, mousepad | mobile, moneypot, monitor |
mo | same five | mobile, moneypot, monitor |
mou | mouse, mousepad | mouse, mousepad |
mous | mouse, mousepad | mouse, mousepad |
mouse | mouse, mousepad | mouse, mousepad |
Start with brute force
Sort the products once. Then for each of the m prefixes, scan the whole sorted list and take the first three that start with the prefix.
That's O(m · n · L) after sorting: each prefix check can compare up to L characters across n products. With n = 1,000 products and a 1,000-letter search word, that's 10⁶ prefix checks, each possibly long. It passes on small inputs but does the same work again for every letter typed.
Building the intuition
Every prefix you type is a path from the root of a trie. All products starting with mou live in the subtree under the node for mou. So each answer is "the three smallest words in some subtree".
Finding the three smallest words in a subtree on every keystroke would mean a DFS each time. Can we precompute it instead?
Here's the trick: insert products in sorted order. When mobile is inserted, it passes through m, mo, mob, …. Then moneypot passes through m and mo. Then monitor. Words arrive alphabetically, so the first three words to pass through a node are exactly that node's three alphabetically smallest words.
So each node just keeps a little list, and appends a word only while the list has fewer than three entries. After building, every answer is ready and waiting at its node.
The second observation makes the query side trivial: once the typed prefix leaves the trie (no product has it), every longer prefix also has no products. From then on, every answer is [].
The optimal approach
- Sort
productsalphabetically. - Build the trie. For each product (with its index
idxin sorted order), walk its letters from the root, creating missing nodes. At every node you pass through, iflen(node.top) < 3, appendidx. - Answer the queries. Start at the root. For each letter of
searchWord:- if we're still in the trie, move to that letter's child (which may be missing);
- if we're in the trie, the answer is the products at
node.top; otherwise[].
The subtle detail: append to top at each node after stepping into it, not at the root. The root would be the empty prefix, which isn't one of the answers. Storing indices instead of copies of the strings keeps memory small, especially in C++.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.top = [] # indices of the (at most 3) smallest products below this node
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
# Insert in sorted order, so the first 3 words to pass through a node
# are exactly its 3 lexicographically smallest completions
products.sort()
root = TrieNode()
for idx, word in enumerate(products):
node = root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
if len(node.top) < 3:
node.top.append(idx)
result = []
node = root
for ch in searchWord:
# Once the typed prefix leaves the trie, it stays gone for every longer prefix
if node is not None:
node = node.children.get(ch)
result.append([] if node is None else [products[i] for i in node.top])
return resultstruct TrieNode {
TrieNode* children[26] = {}; // children[c - 'a']
vector<int> top; // indices of the (at most 3) smallest products below this node
};
class Solution {
public:
vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
// Insert in sorted order, so the first 3 words to pass through a node
// are exactly its 3 lexicographically smallest completions
sort(products.begin(), products.end());
TrieNode* root = new TrieNode();
for (int idx = 0; idx < (int)products.size(); idx++) {
TrieNode* node = root;
for (char ch : products[idx]) {
int i = ch - 'a';
if (node->children[i] == nullptr) {
node->children[i] = new TrieNode();
}
node = node->children[i];
if (node->top.size() < 3) {
node->top.push_back(idx);
}
}
}
vector<vector<string>> result;
TrieNode* node = root;
for (char ch : searchWord) {
// Once the typed prefix leaves the trie, it stays gone for every longer prefix
if (node != nullptr) {
node = node->children[ch - 'a'];
}
vector<string> row;
if (node != nullptr) {
for (int i : node->top) row.push_back(products[i]);
}
result.push_back(row);
}
return result;
}
};class Solution {
private static class TrieNode {
TrieNode[] children = new TrieNode[26]; // children[c - 'a']
List<Integer> top = new ArrayList<>(); // indices of the (at most 3) smallest products below this node
}
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
// Insert in sorted order, so the first 3 words to pass through a node
// are exactly its 3 lexicographically smallest completions
Arrays.sort(products);
TrieNode root = new TrieNode();
for (int idx = 0; idx < products.length; idx++) {
TrieNode node = root;
for (char ch : products[idx].toCharArray()) {
int i = ch - 'a';
if (node.children[i] == null) {
node.children[i] = new TrieNode();
}
node = node.children[i];
if (node.top.size() < 3) {
node.top.add(idx);
}
}
}
List<List<String>> result = new ArrayList<>();
TrieNode node = root;
for (char ch : searchWord.toCharArray()) {
// Once the typed prefix leaves the trie, it stays gone for every longer prefix
if (node != null) {
node = node.children[ch - 'a'];
}
List<String> row = new ArrayList<>();
if (node != null) {
for (int i : node.top) row.add(products[i]);
}
result.add(row);
}
return result;
}
}class TrieNode {
constructor() {
this.children = new Map(); // letter -> TrieNode
this.top = []; // indices of the (at most 3) smallest products below this node
}
}
/**
* @param {string[]} products
* @param {string} searchWord
* @return {string[][]}
*/
var suggestedProducts = function (products, searchWord) {
// Insert in sorted order, so the first 3 words to pass through a node
// are exactly its 3 lexicographically smallest completions
products.sort();
const root = new TrieNode();
products.forEach((word, idx) => {
let node = root;
for (const ch of word) {
if (!node.children.has(ch)) {
node.children.set(ch, new TrieNode());
}
node = node.children.get(ch);
if (node.top.length < 3) {
node.top.push(idx);
}
}
});
const result = [];
let node = root;
for (const ch of searchWord) {
// Once the typed prefix leaves the trie, it stays gone for every longer prefix
if (node !== null) {
node = node.children.get(ch) || null;
}
result.push(node === null ? [] : node.top.map((i) => products[i]));
}
return result;
};Dry run
Sorted products: 0 mobile, 1 moneypot, 2 monitor, 3 mouse, 4 mousepad. The top lists after building:
| Node | Words passing through, in order | top (first 3) |
|---|---|---|
m | 0, 1, 2, 3, 4 | [0, 1, 2] |
mo | 0, 1, 2, 3, 4 | [0, 1, 2] |
mou | 3, 4 | [3, 4] |
mous | 3, 4 | [3, 4] |
mouse | 3, 4 | [3, 4] |
Walking "mouse" reads exactly these rows: [mobile, moneypot, monitor] twice, then [mouse, mousepad] three times.
With products = ["havana"] and search word "tatiana": the root has no t child, so node becomes null on the first letter, and all seven answers are [].
Complexity
- Time: O(n log n · L + S + m). Sorting compares strings of length up to L. Building visits each of the S total letters once. Answering is one step per typed letter, plus copying at most 3 words per answer.
- Space: O(S) for the trie nodes. Each node stores at most 3 indices, so the lists add only O(S) too.
Edge cases and traps
- Forgetting to sort first. The "first three to pass through" are then just the first three in the input, not the smallest.
- Stopping the output early when no match exists. The answer always has
len(searchWord)entries. Pad with empty lists. - Walking from a null node. Once you've fallen off the trie, keep
nodenull and skip the lookup. Don't crash onnull.children. - A product equal to a prefix. If
mouseis a product and you've typedmouse, it's included, and it sorts beforemousepad, because a prefix comes first alphabetically. - Storing all words at every node. That costs O(n · L) per node in the worst case. Cap the list at 3.
Say it in the interview
"Each typed prefix is a node in a trie of the products, and I need the three smallest words under it. If I sort the products first and insert them in that order, the first three words passing through any node are its three smallest, so each node just keeps up to three indices. Then I walk the search word through the trie and read off each node's list. Once I fall off the trie, every remaining answer is empty. That's the sort, plus linear work in the total number of letters."
Follow-ups interviewers ask
- "Can you do it without a trie?" Yes: sort, then for each prefix binary-search for the first product ≥ the prefix and check the next three. Even simpler, keep two pointers
loandhiover the sorted list and narrow them as each letter is typed. - "What if products have popularity scores?" Keep the top 3 by score at each node instead of the first 3. Updates now need a small heap or a re-sort per node.
- "Products are added while users type?" The trie handles inserts in O(L), but each node's top list must be updated with a comparison instead of a simple append.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free