DSA Trie

Search Suggestions System

For each prefix of searchWord, return up to 3 lexicographically smallest matching products.

Medium
Time O(N log N + M) Space O(N)
LeetCode
4 min read
trie sorting binary-search

Problem#

Given a list of products and a searchWord, for each prefix searchWord[0..i] return up to 3 lexicographically smallest products that start with that prefix.

Examples#

  • products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"[["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]].

Constraints#

  • 1 <= products.length <= 1000, 1 <= products[i].length, searchWord.length <= 1000.

Hints#

Hint
Sort products. For each prefix, the matching range is contiguous — find it with binary search.

Approach#

Trie — store all products; at each prefix walk the trie and DFS-collect first 3 words.
Sort + binary search — sort once; for each prefix, lower_bound on the prefix and read at most 3 strings.

After sorting, all products matching a prefix occupy a contiguous range. Use lower_bound to find the start; take up to 3 while the prefix matches.

Solution#

Search Suggestions System
class Solution {
public:
vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
sort(products.begin(), products.end());
vector<vector<string>> ans;
ans.reserve(searchWord.size());
string prefix;
for (char c : searchWord) {
prefix.push_back(c);
auto it = lower_bound(products.begin(), products.end(), prefix);
vector<string> row;
for (int k = 0; k < 3 && it + k != products.end(); ++k) {
const string& p = *(it + k);
if (p.compare(0, prefix.size(), prefix) != 0) break;
row.push_back(p);
}
ans.push_back(std::move(row));
}
return ans;
}
};

Editorial#

Sorting once is O(N log N). Each prefix lookup is O(log N + L) (binary search plus prefix comparison cost). Trie-based solutions are equally valid but with worse constant factors and more memory; the sort approach is the cleanest answer in C++ since std::lower_bound plus compare is just two function calls.

Complexity#

  • Time: O(N log N + sum of |prefix| * 3).
  • Space: O(1) extra beyond the output.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.