1. Filter and Sort per Keystroke
Intuition
Loop through prefix lengths 1 to searchWord.length(). Collect all products where prod.startsWith(prefix). Sort collected list and slice top 3.
When to apply: Basic baseline check.
Algorithm
- Step 1: Prefix
pref = "". - Step 2: For each char in
searchWord: append topref. - Step 3: Filter
matched = [p for p in products if p.startsWith(pref)]. - Step 4: Sort
matchedand take first 3. - Step 5: Append to result.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) { vector<vector<string>> result; string pref = ""; for (char c : searchWord) { pref += c; vector<string> matched; for (const string& p : products) { if (p.rfind(pref, 0) == 0) { matched.push_back(p); } } sort(matched.begin(), matched.end()); if (matched.size() > 3) matched.resize(3); result.push_back(matched); } return result; }}; int main() { Solution sol; vector<string> prods = {"mobile","mouse","moneypot","monitor","mousepad"}; auto res = sol.suggestedProducts(prods, "mouse"); for (const auto& list : res) { for (const string& w : list) cout << w << " "; cout << endl; } return 0;}Time & Space Complexity
- Time complexity:
O(|searchWord| * P log P * L)— Repeats filtering and sorting for every character typed. - Space complexity:
O(P * L)— Holds matching candidate arrays.
Why Brute Force Doesn't Scale:
With 1,000 keystrokes and 1,000 products, naive search runs 1,000,000 checks.
Pre-caching top 3 items answers each keystroke in under 0.01 milliseconds.